% LaTeX source for ``Think OCaml: How to Think Like a Computer Scientist''
% Copyright (c)  2011  Nicolas Monje

% Permission is granted to copy, distribute and/or modify this
% document under the terms of the GNU Free Documentation License,
% Version 1.1  or any later version published by the Free Software
% Foundation; with no Invariant Sections, no Front-Cover Texts,
% and no Back-Cover Texts.

% This distribution includes a file named fdl.tex that contains the text
% of the GNU Free Documentation License.  If it is missing, you can obtain
% it from www.gnu.org or by writing to the Free Software Foundation,
% Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
%

%\documentclass[10pt,b5paper]{book}
\documentclass[10pt]{book}
\usepackage[width=5.5in,height=8.5in,
  hmarginratio=3:2,vmarginratio=1:1]{geometry}

% for some of these packages, you might have to install
% texlive-latex-extra (in Ubuntu)

\usepackage{pslatex}
\usepackage{url}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{amsmath, amsthm, amssymb}
\usepackage{exercise}                        % texlive-latex-extra
\usepackage{makeidx}
\usepackage{setspace}
\usepackage{hevea}                           
\usepackage{upquote}

\newcommand{\thetitle}{Think OCaml: How to Think Like a Computer Scientist}
\newcommand{\theversion}{0.1.1}

\makeindex

\begin{document}

\frontmatter

% LATEXONLY

\input{latexonly}

\newtheorem{ex}{Exercise}[chapter]

\begin{latexonly}

\renewcommand{\blankpage}{\thispagestyle{empty} \quad \newpage}

%\blankpage
%\blankpage

% TITLE PAGES FOR LATEX VERSION

%-half title--------------------------------------------------
\thispagestyle{empty}

\begin{flushright}
\vspace*{2.0in}

\begin{spacing}{3}
{\huge Think OCaml}\\
{\Large How to Think Like a Computer Scientist}
\end{spacing}

\vspace{0.25in}

Version \theversion

\vfill

\end{flushright}

%--verso------------------------------------------------------

\blankpage
\blankpage
%\clearemptydoublepage
%\pagebreak
%\thispagestyle{empty}
%\vspace*{6in}

%--title page--------------------------------------------------
\pagebreak
\thispagestyle{empty}

\begin{flushright}
\vspace*{2.0in}

\begin{spacing}{3}
{\huge Think OCaml}\\
{\Large How to Think Like a Computer Scientist}
\end{spacing}

\vspace{0.25in}

Version \theversion

\vspace{1in}


{
\large Nicholas Monje\\
\large Allen Downey\\
}


\vspace{0.5in}

{\Large Green Tea Press}

{\small Needham, Massachusetts}

%\includegraphics[width=1in]{figs/logo1.eps}
\vfill

\end{flushright}


%--copyright--------------------------------------------------
\pagebreak
\thispagestyle{empty}

{\small
Copyright \copyright~2011 Nicholas Monje.


Printing history:

\begin{description}

\item[April 2002:] First edition of {\em How to Think Like
a Computer Scientist}.

\item[August 2007:] Major revision, changed title to
{\em How to Think Like a (Python) Programmer}.

\item[June 2008:] Major revision, changed title to
{\em Think Python: How to Think Like
a Computer Scientist}.

\item[January 2011:] Translation to OCaml, changed title to
{\em Think OCaml: How to Think Like a Computer Scientist}.

\end{description}

\vspace{0.2in}

\begin{flushleft}
Green Tea Press       \\
9 Washburn Ave \\
Needham MA 02492
\end{flushleft}

Permission is granted to copy, distribute, and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and with no Back-Cover Texts.

The GNU Free Documentation License is available from {\tt www.gnu.org}
or by writing to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307, USA.

The original form of this book is \LaTeX\ source code.  Compiling this
\LaTeX\ source has the effect of generating a device-independent
representation of a textbook, which can be converted to other formats
and printed.

%The \LaTeX\ source for this book is available from
%\url{http://www.thinkpython.com}

Cover image is courtesy of Anumpama Kinagi, all rights reserved.

\vspace{0.2in}

} % end small

\end{latexonly}


% HTMLONLY

\begin{htmlonly}

% TITLE PAGE FOR HTML VERSION

{\Large \thetitle}

{\large Nicholas Monje\\}
{\large Allen Downey\\}

Version \theversion

\setcounter{chapter}{-1}

\end{htmlonly}

\chapter{Preface}

% TODO(monje): write a preface :)

\section*{Contributor List}

Many thanks to Anumpama Kinagi for the use of the cover image.


% TABLE OF CONTENTS
\begin{latexonly}

\tableofcontents

\clearemptydoublepage

\end{latexonly}

% START THE BOOK
\mainmatter


\chapter{The way of the program}

The goal of this book is to teach you to think like a
computer scientist.  This way of thinking combines some of the best features
of mathematics, engineering, and natural science.  Like mathematicians,
computer scientists use formal languages to denote ideas (specifically
computations).  Like engineers, they design things, assembling components
into systems and evaluating tradeoffs among alternatives.  Like scientists,
they observe the behavior of complex systems, form hypotheses, and test
predictions.

\index{problem solving}

The single most important skill for a computer scientist is {\bf
problem solving}.  Problem solving means the ability to formulate
problems, think creatively about solutions, and express a solution clearly
and accurately.  As it turns out, the process of learning to program is an
excellent opportunity to practice problem-solving skills.  That's why
this chapter is called, ``The way of the program.''

On one level, you will be learning to program, a useful
skill by itself.  On another level, you will use programming as a means to
an end.  As we go along, that end will become clearer.

\section{The OCaml programming language}
\index{programming language}
\index{language!programming}

The programming language you will learn is OCaml. OCaml is
an example of a {\bf high-level language}; other high-level languages
you might have heard of are C, C++, Perl, Java and Python.

There are also {\bf low-level languages}, sometimes referred to as ``machine
languages'' or ``assembly languages.''  Loosely speaking, computers
can only execute programs written in low-level languages.  So
programs written in a high-level language have to be processed before
they can run.  This extra processing takes some time, which is a small
disadvantage of high-level languages.

\index{portability}
\index{high-level language}
\index{low-level language}
\index{language!high-level}
\index{language!low-level}

The advantages are enormous.  First, it is much easier to program
in a high-level language.  Programs written in a high-level language
take less time to write, they are shorter and easier to read, and they
are more likely to be correct.  Second, high-level languages are {\bf
portable}, meaning that they can run on different kinds of computers
with few or no modifications.  Low-level programs can run on only one
kind of computer and have to be rewritten to run on another.

Due to these advantages, almost all programs are written in high-level
languages.  Low-level languages are used only for a few specialized
applications.

\index{compile}
\index{interpret}

Two kinds of programs process high-level languages
into low-level languages: {\bf interpreters} and {\bf compilers}.
An interpreter reads a high-level program and executes it, meaning that it
does what the program says.  It processes the program a little at a time,
alternately reading lines and performing computations.

\beforefig
\centerline{\includegraphics[height=0.77in]{figs/interpret.eps}}
\afterfig

\index{source code}
\index{object code}
\index{executable}

A compiler reads the program and translates it completely before the program 
starts running.  In this context, the high-level program is called the {\bf source 
code}, and the translated program is called the {\bf object code} or the {\bf executable}.  
Once a program is compiled, you can execute it repeatedly without further translation.

\beforefig
\centerline{\includegraphics[height=0.77in]{figs/compile.eps}}
\afterfig

One of the nice features of OCaml is that OCaml is both a compiled and an interpreted 
programming language. On the one hand, OCaml can be compiled into an executable file. 
This makes it easier to pass along your program to non-OCaml users, which for a new, 
up-and-coming programming language like OCaml, is a nice feature. On the other hand, 
OCaml can be treated like an interpreted programming language, meaning that an OCaml 
script or OCaml commands can be executed by an interpreter. This is useful for finding 
errors in your code and testing commands and snippets of code. There are two ways to use 
the interpreter: {\bf interactive mode} and {\bf script mode}. In interactive mode, you 
type OCaml commands into the {\bf toplevel} and the interpreter prints the result:

\index{interactive mode}
\index{script mode}

\beforeverb
\begin{verbatim}
# 1+1;;
- : int = 2
\end{verbatim}
\afterverb
%
The octothorp, {\tt \#}, is the {\bf prompt} the interpreter uses to indicate that it is 
ready. The double semi-colons indicates the end of a line. If you type {\tt 1 + 1;;}, the 
interpreter replies {\tt - : int = 2}.

\index{prompt}

Alternatively, you can store code in a file and use the interpreter to execute the contents 
of the file, which is called a {\bf script}.  By convention, OCaml scripts have names that 
end with {\tt .ml}.

\index{script}

\index{testing!interactive mode}

Working in interactive mode is convenient for testing small pieces of code because you can type 
and execute them immediately.  But for anything more than a few lines, you should save your code 
as a script so you can modify and execute it in the future.

\section{The OCaml Toplevel}

Let's take a moment to explain how to use the OCaml toplevel. The toplevel 
works a little differently depending on your operating system. I will cover 
using the toplevel in Windows (7) and Ubuntu (10.04 Karmic). \footnote{Mac users are on their own.}

One thing you will need to use are OCaml commands known as {\bf directives}. 
Directives tell the interpreter or compiler to do specific tasks, like load 
code from a file or exit. A list of some directives  can be found at 
\url{http://caml.inria.fr/pub/docs/manual-ocaml/manual023.html}. One particularly
useful directive is {\tt \verb"#quit;;"}, which does exactly what it sounds like.

\index{Directive}
\index{Toplevel}

\subsection{Ubuntu (10.04)}

First off, you must install the ocaml package and its dependencies. Open the terminal and type:

\beforeverb
\begin{verbatim}
 sudo apt-get install ocaml
\end{verbatim}
\afterverb
It will then likely ask you for your admin password. After the installation is complete, you can 
open the OCaml toplevel simply by typing {\tt ocaml} at the command line.

Once in the toplevel, you can open a script by using the {\tt \#use "{\it filename}";;} directive:

\beforeverb
\begin{verbatim}
# #use "myscript.ml";;
\end{verbatim}
\afterverb

Note that the toplevel's {\bf current directory} \footnote{The {\bf current directory} is the 
directory in which ocaml will look to find files to run, outside of the standard ocaml directories.} 
will be the current directory when you ran it within the terminal. You can change your current directory 
using the {\tt \#cd ``{\it dirname}'';;} directive.

\subsection{Windows (7)}

First you must install OCaml. Go to the OCaml home page (\url{caml.inria.fr}) and go to the Download 
page. Download the appropriate distribution - if you don't know which one to choose, go with the 
Windows binary ``for the port based on the Microsoft toolchain.'' Run the installer and follow the 
directions therein.

You can now run an OCaml toplevel from the windows command line by typing {\tt ocaml}. Alternatively,
OCaml has a very pretty toplevel with some nice features which you can open by running "Objective Caml"
from Windows \verb">" All Programs \verb">" Objective Caml, or open the same program by searching from the windows 
start menu.

Once in the toplevel, you can open a script by using the {\tt \#use "{\it filename}";;} directive:

\beforeverb
\begin{verbatim}
# #use "myscript.ml";;
\end{verbatim}
\afterverb

Note that the toplevel's {\bf current directory} \footnote{The {\bf current directory} is the 
directory in which ocaml will look to find files to run, outside of the standard ocaml directories.} 
will be the current directory when you ran it within the terminal. You can change your current directory 
using the {\tt \#cd "{\it dirname}";;} directive.

\section{What is a program?}

A {\bf program} is a sequence of instructions that specifies how to perform a computation.  The computation 
might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, 
but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely 
enough) compiling a program.

\index{program}

The details look different in different languages, but a few basic instructions appear in just about every 
language:

\begin{description}

\item[input:] Get data from the keyboard, a file, or some other device.

\item[output:] Display data on the screen or send data to a file or other device.

\item[math:] Perform basic mathematical operations like addition and multiplication.

\item[conditional execution:] Check for certain conditions and execute the appropriate sequence of statements.

\item[repetition:] Perform some action repeatedly, usually with some variation.

\end{description}

Believe it or not, that's pretty much all there is to it.  Every program you've ever used, no matter how 
complicated, is made up of instructions that look pretty much like these.  So you can think of programming 
as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are 
simple enough to be performed with one of these basic instructions.

\index{algorithm}

That may be a little vague, but we will come back to this topic when we talk about {\bf algorithms}.

\section{What is debugging?}
\index{debugging}
\index{bug}

Programming is error-prone.  For whimsical reasons, programming errors are called {\bf bugs}\footnote{It's 
not actually true that it's named after a moth found in a computer relay, though that does make for a rather 
amusing story. For more information on etymology, check out \url{http://en.wikipedia.org/wiki/Software_bug}.} 
and the process of tracking them down is called {\bf debugging}.

\index{debugging}
\index{bug}

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful 
to distinguish between them in order to track them down more quickly.

\subsection{Syntax errors}
\index{syntax error}
\index{error!syntax}
\index{error message}

OCaml can only execute a program if the syntax is correct; otherwise, the interpreter displays an error message.  
{\bf Syntax} refers to the structure of a program and the rules about that structure. For example, parentheses 
have to come in matching pairs, so {\tt (1 + 2)} is legal, but {\tt 8)} is a {\bf syntax error}.

\index{parentheses!matching}
\index{syntax}
\index{cummings, e. e.}

In English readers can tolerate most syntax errors, which is why we can read the poetry of e. e. cummings without 
spewing error messages. OCaml is not so forgiving.  If there is a single syntax error anywhere in your program, 
OCaml will display an error message and quit, and you will not be able to run your program. During the first few 
weeks of your programming career, you will probably spend a lot of time tracking down syntax errors.  As you gain 
experience, you will make fewer errors and find them faster.

\subsection{Runtime errors}
\label{runtime}
\index{runtime error}
\index{error!runtime}
\index{exception}
\index{safe language}
\index{language!safe}

The second type of error is a runtime error, so called because the error does not appear until after the 
program has started running. These errors are also called {\bf exceptions} because they usually indicate 
that something exceptional (and bad) has happened.

Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a 
while before you encounter one.

\subsection{Semantic errors}
\index{semantics}
\index{semantic error}
\index{error!semantic}
\index{error message}

The third type of error is the {\bf semantic error}.  If there is a semantic error in your program, it will 
run successfully in the sense that the computer will not generate any error messages, but it will not do the 
right thing.  It will do something else.  Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write.  The meaning of the program 
(its semantics) is wrong. Identifying semantic errors can be tricky because it generally requires you to work 
backward by looking at the output of the program and trying to figure out what it is doing.

\subsection{Experimental debugging}

One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one 
of the most intellectually rich, challenging, and interesting parts of programming.

\index{experimental debugging}
\index{debugging!experimental}

In some ways, debugging is like detective work.  You are confronted with clues, and you have to infer the processes 
and events that led to the results you see.

Debugging is also like an experimental science.  Once you have an idea about what is going wrong, you modify your 
program and try again.  If your hypothesis was correct, then you can predict the result of the modification, and 
you take a step closer to a working program.  If your hypothesis was wrong, you have to come up with a new one.  
As Sherlock Holmes pointed out, ``When you have eliminated the impossible, whatever remains, however improbable, 
must be the truth.'' (A. Conan Doyle, {\em The Sign of Four})

\index{Holmes, Sherlock}
\index{Doyle, Arthur Conan}

For some people, programming and debugging are the same thing.  That is, programming is the process of gradually 
debugging a program until it does what you want.  The idea is that you should start with a program that does {\em 
something} and make small modifications, debugging them as you go, so that you always have a working program.

For example, Linux is an operating system that contains thousands of lines of code, but it started out as a simple 
program Linus Torvalds used to explore the Intel 80386 chip.  According to Larry Greenfield, ``One of Linus's 
earlier projects was a program that would switch between printing AAAA and BBBB.  This later evolved to Linux.'' 
({\em The Linux Users' Guide} Beta Version 1).

\index{Linux}

Later chapters will make more suggestions about debugging and other programming practices.

\section{Formal and natural languages}
\index{formal language}
\index{natural language}
\index{language!formal}
\index{language!natural}

{\bf Natural languages} are the languages people speak, such as English, Spanish, and French.  They were not 
designed by people (although people try to impose some order on them); they evolved naturally.

{\bf Formal languages} are languages that are designed by people for specific applications.  For example, the 
notation that mathematicians use is a formal language that is particularly good at denoting relationships 
among numbers and symbols.  Chemists use a formal language to represent the chemical structure of molecules.  
And most importantly:

\begin{quote}
{\bf Programming languages are formal languages that have been designed to express computations.}
\end{quote}

Formal languages tend to have strict rules about syntax.  For example, $3 + 3 = 6$ is a syntactically correct 
mathematical statement, but $3 + = 3 \mbox{\$} 6$ is not.  $H_2O$ is a syntactically correct chemical formula, 
but $_2Zz$ is not.

Syntax rules come in two flavors, pertaining to {\bf tokens} and structure.  Tokens are the basic elements of 
the language, such as words, numbers, and chemical elements.  One of the problems with $3 + = 3 \mbox{\$} 6$ 
is that $\$$ is not a legal token in mathematics (at least as far as I know).  Similarly, $_2Zz$ is not legal 
because there is no element with the abbreviation $Zz$.

\index{token}
\index{structure}

The second type of syntax error pertains to the structure of a statement; that is, the way the tokens are 
arranged.  The statement $3 + = 3 \mbox{\$} 6$ is illegal because even though $+$ and $=$ are legal tokens, 
you can't have one right after the other.  Similarly, in a chemical formula the subscript comes after the 
element name, not before.

\begin{ex}
Write a well-structured English sentence with invalid tokens in it.  Then write another sentence with all 
valid tokens but with invalid structure.
\end{ex}

When you read a sentence in English or a statement in a formal language, you have to figure out what the 
structure of the sentence is (although in a natural language you do this subconsciously).  This process 
is called {\bf parsing}.

\index{parse}

For example, when you hear the sentence, ``The penny dropped,'' you understand that ``the penny'' is the 
subject and ``dropped'' is the predicate.  Once you have parsed a sentence, you can figure out what it 
means, or the semantics of the sentence.  Assuming that you know what a penny is and what it means to 
drop, you will understand the general implication of this sentence.

Although formal and natural languages have many features in common---tokens, structure, syntax, and 
semantics---there are some differences:

\index{ambiguity}
\index{redundancy}
\index{literalness}

\begin{description}

\item[ambiguity:] Natural languages are full of ambiguity, which people deal with by using contextual 
clues and other information. Formal languages are designed to be nearly or completely unambiguous, which 
means that any statement has exactly one meaning, regardless of context.

\item[redundancy:] In order to make up for ambiguity and reduce misunderstandings, natural languages employ 
lots of redundancy.  As a result, they are often verbose.  Formal languages are less redundant and more 
concise.

\item[literalness:] Natural languages are full of idiom and metaphor. If I say, ``The penny dropped,'' 
there is probably no penny and nothing dropping\footnote{This idiom means that someone realized something 
after a period of confusion.}.  Formal languages mean exactly what they say.

\end{description}

People who grow up speaking a natural language---everyone I know---often have a hard time adjusting to 
formal languages.  In some ways, the difference between formal and natural language is like the 
difference between poetry and prose, but more so:

\index{poetry}
\index{prose}

\begin{description}

\item[Poetry:] Words are used for their sounds as well as for their meaning, and the whole poem 
together creates an effect or emotional response.  Ambiguity is not only common but often deliberate.

\item[Prose:] The literal meaning of words is more important, and the structure contributes more 
meaning.  Prose is more amenable to analysis than poetry but still often ambiguous.

\item[Programs:] The meaning of a computer program is unambiguous and literal, and can be understood 
entirely by analysis of the tokens and structure.

\end{description}

Here are some suggestions for reading programs (and other formal languages).  First, remember that 
formal languages are much more dense than natural languages, so it takes longer to read them.  Also, 
the structure is very important, so it is usually not a good idea to read from top to bottom, left 
to right.  Instead, learn to parse the program in your head, identifying the tokens and interpreting 
the structure.  Finally, the details matter.  Small errors in spelling and punctuation, which you can 
get away with in natural languages, can make a big difference in a formal language.

\section{The first program}
\label{hello}

\index{Hello, World}

Traditionally, the first program you write in a new language is called ``Hello, World!'' 
because all it does is display the words, ``Hello, World!''  In Ocaml, one version looks 
like this:

\beforeverb
\begin{verbatim}
print_string "Hello, World!\n";;
\end{verbatim}
\afterverb

This is an example of a {\bf print statement}, which doesn't actually print anything on paper. 
It displays a value on the screen.  In this case, the result is:

\beforeverb
\begin{verbatim}
Hello, World!
- : unit = ()
\end{verbatim}
\afterverb

The quotation marks in the program mark the beginning and end of the text to be displayed; they 
don't appear in the result. The ``\verb"\n"'' is an {\bf escape character} \footnote{An escape character 
is a special character within a string denoted by a ``whack'' (``\textbackslash'') followed by a character or 
series of characters that results in a special character, such as a new line.}, specifically the 
newline character, which tells the output to move to a new line.

\index{escape character}
\index{quotation mark}
\index{print statement}
\index{statement!print}

There's another, more general print statement called ``printf,'' which lets you do more than {\tt print\verb"_"string}.
Printf comes from it's own {\bf module}, called Printf, meaning you call printf by typing ``Printf.printf.' 
Modules are extensions of OCaml that often contain useful functions. Printf is a standard module, meaning
it comes prepackaged with most OCaml installations. You can look up printf on your own if you're interested.

Alternatively, you can import the module by using the \verb"#use" directive:

\beforeverb
\begin{verbatim}
# #use "printf.ml"
\end{verbatim}
\afterverb
%
And then call printf simply as {\tt printf}. However, importing a module generally isn't advised  unless you're really going to use functions from that module a lot.

\index{module}

Really, we could simply just type ``Hello, World!'' and get the result ``{\tt - : string = ''Hello, World!''.}''

Some people judge the quality of a programming language by the simplicity of the ``Hello, World!'' program.  By this standard, OCaml does \footnote{Or can do, anyway. There are about as many different OCaml ``Hello, World!'' programs as there are OCaml programmers, all arguably equally valid.} about as well as possible.

\section{Functional, as opposed to...?}

\index{Functional Programming}
\index{Programming!Functional}
\index{Programming Paradigms}
\index{Programming Paradigms!Functional}
\index{Programming Paradigms!Object-Oriented}

{\bf Functional Programming} is a programming paradigm where the function is a
first-class citizen. Now, this is of course a silly definition, but
it's the best we can really do for now.

Another popular programming paradigm is {\bf
  Object-Oriented}. Languages that are object-oriented, such as C++
and Python, focus rather on having ``objects'' and changing
them. ``Object'' is really kind of a blanket term for all kinds of
different, often custom, ways of storing data.

OCaml is mostly a functional programming language. However, OCaml has support for some level of object-oriented programming, unlike it's predecessor Caml. The ``O'' in OCaml stands for ``Objective''.\footnote{``Caml'' once stood for ``Categorical Abstract Machine Language'' but it doesn't any more. Now it just represents an even-toed ungulate with humps on its back.}

\section{Debugging}
\index{debugging}

It is a good idea to read this book in front of a computer so you can try out the examples as you go.  You can run most of the examples in interactive mode, but if you put the code into a script, it is easier to try out variations.

Whenever you are experimenting with a new feature, you should try to make mistakes.  For example, in the ``Hello, world!'' program, what happens if you leave out one of the quotation marks?  What if you leave out both?  What if you spell {\tt print\verb"_"string} wrong?

\index{error message}

This kind of experiment helps you remember what you read; it also helps with debugging, because you get to know what the error messages mean. It is better to make mistakes now and on purpose than later and accidentally.

Programming, and especially debugging, sometimes brings out strong emotions.  If you are struggling with a difficult bug, you might feel angry, despondent or embarrassed.

There is evidence that people naturally respond to computers as if they were people\footnote{See Reeves and Nass, {\it The Media Equation: How People Treat Computers, Television, and New Media Like Real People and Places}.}.  When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people.

\index{debugging!emotional response}
\index{emotional debugging}

Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.

Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses.  And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.

Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming.  At the end of each chapter there is a debugging section, like this one, with my thoughts about debugging.  I hope they help!


\section{Glossary}

\begin{description}

\item[problem solving:]  The process of formulating a problem, finding a solution, and expressing the solution.
\index{problem solving}

\item[high-level language:]  A programming language like OCaml that is designed to be easy for humans to read and write.
\index{high-level language}

\item[low-level language:]  A programming language that is designed to be easy for a computer to execute; also called ``machine language'' or ``assembly language.''
\index{low-level language}

\item[portability:]  A property of a program that can run on more than one kind of computer.
\index{portability}

\item[interpret:]  To execute a program in a high-level language by translating it one line at a time.
\index{interpret}

\item[compile:]  To translate a program written in a high-level languag into a low-level language all at once, in preparation for later execution.
\index{compile}

\item[source code:]  A program in a high-level language before being compiled.
\index{source code}

\item[object code:]  The output of the compiler after it translates the program.
\index{object code}

\item[executable:]  Another name for object code that is ready to be executed.
\index{executable}

\item[prompt:] Characters displayed by the interpreter to indicate that it is ready to take input from the user.
\index{prompt}

\item[script:] A program stored in a file (usually one that will be interpreted).
\index{script}

\item[interactive mode:] A way of using the OCaml interpreter by typing commands and expressions at the prompt.
\index{interactive mode}

\item[script mode:] A way of using the OCaml interpreter to read and execute statements in a script.
\index{script mode}

\item[toplevel:] The interface you interact with when working with the interpreter.
\index{toplevel}

\item[program:] A set of instructions that specifies a computation.
\index{program}

\item[algorithm:]  A general process for solving a category of problems.
\index{algorithm}

\item[bug:]  An error in a program.
\index{bug}

\item[debugging:]  The process of finding and removing any of the three kinds of programming errors.
\index{debugging}

\item[syntax:]  The structure of a program.
\index{syntax}

\item[syntax error:]  An error in a program that makes it impossible to parse (and therefore impossible to interpret).
\index{syntax error}

\item[exception:]  An error that is detected while the program is running.
\index{exception}

\item[semantics:]  The meaning of a program.
\index{semantics}

\item[semantic error:]   An error in a program that makes it do something other than what the programmer intended.
\index{semantic error}

\item[natural language:]  Any one of the languages that people speak that evolved naturally.
\index{natural language}

\item[formal language:]  Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.
\index{formal language}

\item[token:]  One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.
\index{token}

\item[parse:]  To examine a program and analyze the syntactic structure.
\index{parse}

\item[print statement:]  An instruction that causes the OCaml interpreter to display a value on the screen.
\index{print statement}
\index{statement!print}


\end{description}


\section{Exercises}

\begin{ex}
Use a web browser to go to the OCaml website \url{caml.inria.fr}. This page contains information about OCaml (and Caml Light) and links to OCaml-related pages, and it gives you the ability to search the Ocaml documentation.

Note that OCaml, like all good things, comes from France (hence the .fr in the url).

\index{documentation}
\index{caml.inria.fr}
\end{ex}

\begin{ex}
Open the OCaml toplevel and create a ``Hello, World!'' program in interactive mode.

Now, create a script called ``hello.ml'' that is a ``Hello, World!'' program and run it.

Experiment with several different methods of writing this program. In particular, write at least one method using the Printf module. Use the OCaml documentation online to understand enough of this module to do so.
\end{ex}


\chapter{Variables and Expressions}

\section{Values and types}
\index{value}
\index{type}
\index{string}

A {\bf value} is one of the basic things a program works with, like a letter or a number.  Some values we have seen so far are {\tt 1}, {\tt 2}, and {\tt "Hello, World!"}.

These values belong to different {\bf types}: {\tt 2} is an integer, and {\tt "Hello, World!"} is a {\bf string}, so-called because it contains a ``string'' of letters. You (and the interpreter) can identify strings because they are enclosed in double quotation marks.

\index{quotation mark}

You've already seen \verb"print_string". There's also a print statement for integers:

\beforeverb
\begin{verbatim}
# print_int 4;;
4- : unit = ()
\end{verbatim}
\afterverb

If you are not sure what type a value has, the interpreter will tell you.

\beforeverb
\begin{verbatim}
# let a = 1;;
val a : int = 1;;
# let foo = "Hello, World!"
val foo : string = "Hello, World!"
\end{verbatim}
\afterverb
%
Not surprisingly, strings belong to the type {\tt string} and
integers belong to the type {\tt int}.  Less obviously, numbers
with a decimal point belong to a type called {\tt float},
because these numbers are represented in a
format called {\bf floating-point}.

\index{type}
\index{string type}
\index{type!str}
\index{int type}
\index{type!int}
\index{float type}
\index{type!float}

\beforeverb
\begin{verbatim}
# let a = 3.2;;
val a : float = 3.2
\end{verbatim}
\afterverb

There's also a separate type called ``char,'' which is short for ``character.'' 
A char is like a string, but it's only one character long (hence the name), and it's surrounded 
by single quotes instead of double quotes. In fact, strings are comprised of lists
of chars. \footnote{A note on pronunciation: most often, ``char'' is pronounced like in charcoal. 
It's less standard, but I personally prefer to pronounce it like it appears in character, since 
that's where it came from.} Usually, you'll use strings, but if you really only need one character, 
chars use less memory.

\index{char type}
\index{type!char}

\beforeverb
\begin{verbatim}
# let foo = 'a';;
val foo : char = 'a'
\end{verbatim}
\afterverb

If you attempt to make a char that's more than one character in length, you get a syntax error:

\beforeverb
\begin{verbatim}
# let foo = 'ab';;
Error: Syntax error
\end{verbatim}
\afterverb

If you enclose a number in quotes, OCaml will infer that it is a char or string, 
depending on the number of quotes.

When you type a large integer, you might be tempted to use commas
between groups of three digits, as in {\tt 1,000,000}.  This is not a
legal integer in OCaml, but it is legal:

\beforeverb
\begin{verbatim}
>>> 1,000,000
- : int * int * int = (1, 0, 0)
\end{verbatim}
\afterverb

Well, that's not what we expected at all!  OCaml interprets {\tt  1,000,000} 
as a comma-separated sequence of integers. Nevermind the type of this object; 
we'll get to it later.

\index{semantic error}
\index{error!semantic}
\index{error message}

This is the first example we have seen of a semantic error: the code
runs without producing an error message, but it doesn't do the
``right'' thing.

There's also one more type, called {\bf unit}, represented as (). This represents 
a sort of ``void''  or ``empty'' value. You'll see where this pops up, and can be useful, later.

\index{type!unit}
\index{unit type}

\section{Variables}
\index{variable}
\index{assignment statement}
\index{statement!assignment}

One of the most powerful features of a programming language is the
ability to manipulate {\bf variables}.  A variable is a name that
refers to a value. In OCaml, variables {\it really} refer to expressions, 
but don't worry about that for now.

An {\bf assignment statement} creates new variables and gives
them values:

\beforeverb
\begin{verbatim}
# let message = "Don't forget to buy milk.";;
val message : string = "Don't forget to buy milk."
# let n = 17;;
val n : int = 17
# let pi = 3.14159265;;
val pi : float = 3.14159265
\end{verbatim}
\afterverb

This example makes three assignments.  The first assigns a string
to a new variable named {\tt message};
the second gives the integer {\tt 17} to {\tt n}; the third
assigns the (approximate) value of $\pi$ to {\tt pi}.

\index{state diagram}
\index{diagram!state}

A common way to represent variables on paper is to write the name with
an arrow pointing to the variable's value.  This kind of figure is
called a {\bf state diagram} because it shows what state each of the
variables is in (think of it as the variable's state of mind).
This diagram shows the result of the previous example:

\beforefig
\centerline{\includegraphics{figs/state2.eps}}
\afterfig

To display the value of a variable, you can simply type it in the toplevel:

\beforeverb
\begin{verbatim}
# n;;
- : int = 17
# pi;;
- : float = 3.14159265
\end{verbatim}
\afterverb

\section{Variable names and keywords}
\index{keyword}

Programmers generally choose names for their variables that
are meaningful---they document what the variable is used for.

Variable names can be arbitrarily long.  They can contain
both letters and numbers, but they have to begin with a letter.
It is legal to use uppercase letters, but it is a good idea
to begin variable names with a lowercase letter (you'll
see why later).

The underscore character (\verb"_") can appear in a name.
It is often used in names with multiple words, such as
\verb"my_name" or \verb"airspeed_of_unladen_swallow", or 
to denote subscripts, such as \verb"y_0" as an initial 
condition. So can an apostraphe (\verb"'"), such as 
\verb"h'".

\index{underscore character}

If you give a variable an illegal name, you get a syntax 
error:

\beforeverb
\begin{verbatim}
# let 17h = 17*17;;
Error: Syntax error
# let more@ = "hello";;
Error: Sytax error
# let class = 2;;
Error: Syntax error
\end{verbatim}
\afterverb

At the toplevel, OCaml will be nice and even underline 
where the error occured for you.

{\tt 7h} is illegal because it does not begin with a letter.
{\tt more@} is illegal because it contains an illegal character, {\tt
@}.  But what's wrong with {\tt class}?

It turns out that {\tt class} is one of OCaml's {\bf keywords}.  The
interpreter uses keywords to recognize the structure of the program,
and they cannot be used as variable names. The full list of keywords 
can be found online here: 
\url{http://caml.inria.fr/pub/docs/manual-ocaml/manual044.html}.

\index{keyword}

You'll get a really interesting error if you try to use just a 
number as a variable:

\beforeverb
\begin{verbatim}
# let 17 = 2;;
Warning P: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
0
Exception: Match_failure ("", 8, -17).
\end{verbatim}
\afterverb

That's fun. Technically, this is a semantic error causing a 
syntax error. This will make a little more sense later when
we talk about pattern-matching.

\section{Operators and operands}
\index{operator, arithmetic}
\index{arithmetic operator}
\index{operand}
\index{expression}

{\bf Operators} are special symbols that represent computations like
addition and multiplication.  The values the operator is applied to
are called {\bf operands}.

\index{operator}

In OCaml, operators are {\bf strictly typed}, meaning you can't use an integer operator
for a float, or vice versa. OCaml, unlike some other programming languages, won't
even infer that you meant a float when you put an int, or vice versa. This can make
debugging type errors much simpler, though it seems like a pain at first.

\index{Strictly typed}

For integers, the operators {\tt +}, {\tt -}, {\tt *}, and {\tt /}
perform addition, subtraction, multiplication, and division, as in 
the following examples:

\beforeverb
\begin{verbatim}
20+32   hour-1   hour*60+minute   minute/60  (5+9)*(15-7)
\end{verbatim}
\afterverb

For floating-points, the operators are the same, but followed by a period, namely 
{\tt +.}, {\tt -.}, {\tt *.}, and {\tt /.}. There is also a floating point operator for
exponentiation, namely {\tt **}. There is no integer exponention, probably because an integer
raised to a negative integer would result in a non-integer. \footnote{This is not to say that 
a function can't take two integers and return a float.}

In some other languages, \verb"^" is used for exponentiation, but
in OCaml it is used for string concatenation, meaning the two strings 
are added end-to-start, such as in the following example:

\beforeverb
\begin{verbatim}
 # "Hello, "^"World!";;
- : string = "Hello, World!"
\end{verbatim}
\afterverb

Don't forget to put a space somewhere so your words are separated 
when you concatenate.

You can change an int to a float or vice versa using the 
OCaml functions \verb"float_of_int" or \verb"int_of_float", like so:

\beforeverb
\begin{verbatim}
 float_of_int x;; int_of_float x;;
\end{verbatim}
\afterverb

I'll leave determining which is which as an exercise to the reader.

\section{Expressions}

An {\bf expression} is a combination of values, variables, operators
and functions that returns a particular value. A value all by itself 
is an expression, and so is a variable, so the following are all legal 
expressions (assuming that the variable {\tt x} has been assigned a value):

\index{expression}
\index{evaluate}

\beforeverb
\begin{verbatim}
17;;
x;;
x + 17;;
\end{verbatim}
\afterverb
%
If you type an expression in interactive mode, the interpreter
{\bf evaluates} it and displays the result:

\beforeverb
\begin{verbatim}
# 1 + 1;;
- : int = 2
\end{verbatim}
\afterverb

\index{subexpressions}
Expressions can, and often do,\footnote{Any expression with more than just a value or 
variable technically contains subexpressions.} contain other expressions, called {\bf 
subexpressions}. When evaluating the value of the expression, the OCaml interpreter 
will evaluate the embedded expression and substitute it in to the larger expression. 
In OCaml, and many other function-oriented languages, everything must be an expression. 
Everything up to a double semi-colon ({\tt ;;}) must be exactly one expression, with 
arbitrarily many sub-expressions.

\begin{ex}
Type the following statements in the OCaml interpreter to see
what they do:

\beforeverb
\begin{verbatim}
5;;
let x = 5;;
x + 1;;
\end{verbatim}
\afterverb
%
Now put the same statements into a script and run it.  What
is the output?
\end{ex}

\section{Variables as Expressions, and References}

\index{Variables!References}
\index{References}

Now, this is where I admit that I lied to you a little bit.

Remember how I said that the expression ``let x = 3;;'' assigns
the values of `3' to the variable `x'? Well, that's not
entirely true. In fact, it's not true at all.

What really happens when I say ``let x = 3;;'' is that the {\it expression}
`3' is represented by `x'. `x' becomes kind of a shorthand way of writing `3'.

One of the side effects of this is that you can't change the value of a variable.
So, really, in some sense, they shouldn't be called variables at all.

\section{Scope}

Now, I said you couldn't change the value of variables, but in some senses it looks like you can.

\index{Scope}

\beforeverb
\begin{verbatim}
 # let x = 2;;
val x : int = 2
 # let x = 3;;
val x : int = 3;;
 # x;;
- : x = 3
\end{verbatim}
\afterverb

See? The value of `x' changed! Didn't it?

\index{scope}
Actually, the answer is no, it didn't. What we have here is a problem of {\bf scope}. You see, variables
all act within certain bounds, or on certain levels within a program. Every time we say ``let'', it kind of
creates a new ``level'' of the program, within which only certain variables can be accessed. This brings up
let's counterpart, `in'. The best way to explain `in' is with an example.

\beforeverb
\begin{verbatim}
 # let x = 2;;
val x : int = 2
 # let x = 3 in x+1;;
- : int = 4
 # x;;
- : int = 2
\end{verbatim}
\afterverb

Now, didn't see that last bit coming, did you? When you use ``let... in...;;'', the value assigned by the let only
exists within the expression after in. This is called a ``let-in-binding''.

\index{let}
\index{in}

\begin{ex}
 Play around with scope a little bit in the command line.

 See if you can predict the outcome of the following:
 
 \newcounter{exno}
\begin{list}{\arabic{exno}}{}
  \item
 \beforeverb
 \begin{verbatim}
  # let x = 2 in x+1;;
  # let x = 3 in x+1;;
  # x;;
 \end{verbatim}
 \afterverb
   \item 
 \beforeverb
 \begin{verbatim}
  # let x = 2;;
  # let y = 3 in let x = 2 in x+y;;
  # x;;
  # y;;
 \end{verbatim}
 \afterverb
\end{list}

Now try them out in the interpreter and see if you were right!
\end{ex}


\section{Order of operations}
\index{order of operations}
\index{rules of precedence}
\index{PEMDAS}

When more than one operator appears in an expression, the order of
evaluation depends on the {\bf rules of precedence}.  For
mathematical operators, OCaml follows mathematical convention.
The acronym {\bf PEMDAS} is a useful way to
remember the rules:

\index{parentheses!overriding precedence}

\begin{itemize}

\item {\bf P}arentheses have the highest precedence and can be used 
to force an expression to evaluate in the order you want. Since
expressions in parentheses are evaluated first, {\tt 2 * (3-1)} is 4,
and {\tt (1.+.1.)**(5.-.2.)} is 8.. You can also use parentheses to make an
expression easier to read, as in {\tt (minute * 100) / 60}, even
if it doesn't change the result.

\item {\bf E}xponentiation has the next highest precedence, so
{\tt 2.**1.+.1.} is 3., not 4., and {\tt 3.*1.**3.} is 3., not 27..

\item {\bf M}ultiplication and {\bf D}ivision have the same precedence,
which is higher than {\bf A}ddition and {\bf S}ubtraction, which also
have the same precedence.  So {\tt 2*3-1} is 5, not 4, and
{\tt 6+4/2} is 8, not 5.

\item Operators with the same precedence are evaluated from left to 
right.  So in the expression {\tt degrees /. 2. * pi}, the division
happens first and the result is multiplied by {\tt pi}.  
To divide by $2 \pi$, you can use parentheses or write {\tt degrees /. 2. /. pi}.

\end{itemize}

Technically speaking, all operations in the programming language follow some sort
of order of operations. However, you don't really need to know more than that 
parentheses override all that precedence. In fact, if you need to know more about
the order of operations than the above mathematical rules, then you're not making
your code clear enough and should use parentheses to make things more clear.

\section{String operations}
\index{string!operation}
\index{operator!string}

You cannot perform mathematical operations on strings, even
if the strings look like numbers, so the following are illegal:

\beforeverb
\begin{verbatim}
"2"-"1"    "eggs"/"easy"    "third"*"a charm"  "you"+"me"
\end{verbatim}
\afterverb

In OCaml, an operator cannot be used for two things. In some languages,
for example Python, operators can be {\bf overloaded}, meaning they do different
things in different situations (i.e., `+' can be used for string concatenation).
In OCaml, this is not the case.

\index{operator!overloading}

\section{Comments}
\index{comment}

As programs get bigger and more complicated, they get more difficult
to read.  Formal languages are dense, and it is often difficult to
look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain
in natural language what the program is doing.  These notes are called
{\bf comments}, and they start with a \verb"(*" and end with a \verb"*)":

\beforeverb
\begin{verbatim}
(* compute the percentage of the hour that has elapsed *)
percentage = (minute * 100) / 60
\end{verbatim}
\afterverb

Everything between the parentheses will be ignored by the compiler. 
You can also put comments at the end, or even in the middle, of a 
line of code:

\beforeverb
\begin{verbatim}
 # let x = 2;; (* I'm a comment! *)
val x : int = 2
 # let x (* Hi, mom! *) = 3;;
val x = 3
\end{verbatim}
\afterverb

Of course, putting comments in the middle of expressions like that can be really 
annoying to read.

Comments are most useful when they document non-obvious features of
the code.  It is reasonable to assume that the reader can figure out
{\em what} the code does; it is much more useful to explain {\em why}.

This comment is redundant with the code and useless:

\beforeverb
\begin{verbatim}
let v = 5;;     (* assign 5 to v *)
\end{verbatim}
\afterverb
%
This comment contains useful information that is not in the code:

\beforeverb
\begin{verbatim}
let v = 5;;     (* velocity in meters/second. *)
\end{verbatim}
\afterverb
%
Good variable names can reduce the need for comments, but
long names can make complex expressions hard to read, so there is
a tradeoff.

\section{Debugging}
\index{debugging}

At this point the syntax error you are most likely to make is
an illegal variable name, like {\tt class}, which
is a keyword, or \verb"odd.job" and \verb"hack_and_/", which contain
illegal characters.

\index{syntax error}
\index{error!syntax}

For syntax errors, the error messages don't help much.
The most common message is {\tt SyntaxError: invalid 
syntax} which is not very informative.

\index{error message}
\index{use before def}
\index{exception}
\index{runtime error}
\index{error!runtime}

The runtime error you are most likely to make is a ``unbound value'' that is,
trying to use a variable before you have assigned
a value.  This can happen if you spell a variable name wrong:

\beforeverb
\begin{verbatim}
 # let principal = 327.68;;
val principal : float = 327.68
 # let interest = principle *. rate;;
Error: Unbound value principle
\end{verbatim}
\afterverb

Variables names are case sensitive, so {\tt LaTeX} is not the
same as {\tt latex}.

\index{case-sensitivity, variable names}
\index{semantic error}
\index{error!semantic}

At this point the most likely cause of a semantic error is
the order of operations.  For example, to evaluate $\frac{1}{2 \pi}$,
you might be tempted to write

\beforeverb
\begin{verbatim}
 # 1. /. 2. *. pi;;
\end{verbatim}
\afterverb
%
But the division happens first, so you would get $\pi / 2$, which
is not the same thing!  There is no way for OCaml
to know what you meant to write, so in this case you don't
get an error message; you just get the wrong answer.

\index{order of operations}

Another semantic error you might encounter is a scope error.
For example, assigning a variable for one scope and trying to use it
in another:

\beforeverb
\begin{verbatim}
 # let devil = -1;;
val a : int = -1
 # let god = 1 in god+devil;;
- : int = 0;;
 # god+devil;;
Error: unbound value god
\end{verbatim}
\afterverb

The last common semantic error I'll mention now is attempting to create
a variable name with a space in it, which OCaml interprets as a function
definition:

\beforeverb
\begin{verbatim}
# let bad name = 5;;
val bad : 'a -> int = <fun>
# bad 2;;
- : int = 4
# bad "Please, anything but 4!";;
- : int = 4
\end{verbatim}
\afterverb

What you've done is written a function {\tt bad} that takes one argument of 
any type and always returns {\tt 4}. This will make more sense when we see 
functions next chapter.

\section{Glossary}

\begin{description}

\item[value:]  One of the basic units of data, like a number or string, 
that a program manipulates.
\index{value}

\item[type:] A category of values.  The types we have seen so far
are integers (type {\tt int}), floating-point numbers (type {\tt
float}), strings (type {\tt str}), characters (type {\tt char}), and 
the unit type (type {\tt unit}, {\tt ()}).
\index{type}

\item[integer:] A type that represents whole numbers.
\index{integer}

\item[floating-point:] A type that represents numbers with fractional
parts.
\index{floating-point}

\item[string:] A type that represents sequences of characters.
\index{string}

\item[character: ] A type that represents a single character.
\index{character}

\item[unit type: ] A null or empty type.
\index{unit type}

\item[variable:]  A name that refers to a value. Actually, acts as shorthand for an expression.
\index{variable}

\item[statement:]  A section of code that represents a command or action.  So
far, the statements we have seen are assignments and print statements.
\index{statement}

\item[assignment:]  A statement that assigns a value to a variable.
\index{assignment}

\item[state diagram:]  A graphical representation of a set of variables and the
expressions they refer to.
\index{state diagram}

\item[keyword:]  A reserved word that is used by the compiler to parse a
program; you cannot use keywords like {\tt if}, {\tt  class}, and {\tt while} as
variable names.
\index{keyword}

\item[operator:]  A special symbol that represents a simple computation like
addition, multiplication, or string concatenation.
\index{operator}

\item[operand:]  One of the values on which an operator operates.
\index{operand}

\item[expression:]  A combination of variables, operators, and values that
represents a single result value.
\index{expression}

\item[evaluate:]  To simplify an expression by performing the operations
in order to yield a single value.

\item[rules of precedence:]  The set of rules governing the order in which
expressions involving multiple operators and operands are evaluated.
\index{rules of precedence}
\index{precedence}

\item[concatenate:]  To join two operands end-to-end.
\index{concatenation}

\item[comment:]  Information in a program that is meant for other
programmers (or anyone reading the source code) and has no effect on the
execution of the program.
\index{comment}

\end{description}


\section{Exercises}

\begin{ex}
Assume that we execute the following assignment statements:

\begin{verbatim}
let width = 17;;
let height = 12.0;;
let delimiter = '.';;
\end{verbatim}

For each of the following expressions, write the value of the
expression and the type (of the value of the expression).

\begin{enumerate}

\item {\tt width/2}

\item {\tt width/.2.0}

\item {\tt height/3}

\item {\tt 1 + 2 * 5}

\item {\tt delimiter * 5}

\end{enumerate}

Use the OCaml interpreter to check your answers.
\end{ex}

\begin{ex}
Practice using the OCaml interpreter as a calculator: 
\index{calculator}

\begin{enumerate}

\item The volume of a sphere with radius $r$ is $\frac{4}{3} \pi r^3$.
  What is the volume of a sphere with radius 5?  Hint: 392.6 is wrong!

\item Suppose the cover price of a book is \$24.95, but bookstores get a
  40\% discount.  Shipping costs \$3 for the first copy and 75 cents
  for each additional copy.  What is the total wholesale cost for
  60 copies?

\item If I leave my house at 6:52 am and run 1 mile at an easy pace
  (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at
  easy pace again, what time do I get home for breakfast?

\index{running pace}

\end{enumerate}
\end{ex}

\chapter{Functions}
\label{funcchap}

\section{Function calls}
\label{functionchap}
\index{function call}

In the context of functional programming, a {\bf function} is a named 
expression that performs a computation.  When you define a function,
you specify the name and the expression.  Later, you can ``call'' the 
function by name.  We have already seen one example of a {\bf function 
call}:

\beforeverb
\begin{verbatim}
# float_of_int 32;;
- : float = 32.
\end{verbatim}
\afterverb
%
The name of the function is {\tt \verb"float_of_int"}.  The expression that follows
is called the {\bf argument} of the function.  The result, for this
function, is a floating-point version of the integer argument. There is, of course, the
inverse function,\verb"int_of_float". There are other type conversion functions, too, such as
\verb"string_of_int" and \verb"string_of_float" and their respective inverses.

It is common to say that a function ``takes'' an argument and ``returns''
a result.  The result is called the {\bf return value}.

\index{argument}
\index{return value}

\section{Math functions}
\index{math function}
\index{function, math}

OCaml provides most of the familiar mathematical functions, including
the trig functions and their inverses, log (natural log) and base-10 log.
Naturally, they all take float arguments, not integers.

\beforeverb
\begin{verbatim}
# let ratio = signal_power /. noise_power;
# decibels = 10. *. log10 ratio;;

# radians = 0.7;;
# height = sin radians;;
\end{verbatim}
\afterverb
%
The first example computes the base-10 logarithm of the
signal-to-noise ratio.

\index{log function}
\index{function!log}
\index{sine function}
\index{radian}
\index{trigonometric function}
\index{function, trigonometric}

The second example finds the sine of {\tt radians}.  The name of the
variable is a hint that {\tt sin} and the other trigonometric
functions ({\tt cos}, {\tt tan}, etc.)  take arguments in radians. To
convert from degrees to radians, divide by 360 and multiply by $2
\pi$:

\beforeverb
\begin{verbatim}
# let degrees = 45.;;
# let pi = 4. *. atan 1.0;;
# let radians = degrees /. 360. *. 2. *. pi;;
# sin radians;;
0.707106781187
\end{verbatim}
\afterverb
%

If you know
your trigonometry, you can check the previous result by comparing it to
the square root of two divided by two:

\index{sqrt function}
\index{function!sqrt}

\beforeverb
\begin{verbatim}
# (sqrt 2.) /. 2.0
0.707106781187
\end{verbatim}
\afterverb

\section{Composition}
\index{composition}

So far, we have looked at the elements of a program---variables,
expressions, and statements---in isolation, without talking about how to
combine them.

One of the most useful features of programming languages is their
ability to take small building blocks and {\bf compose} them.  For
example, the argument of a function can be any kind of expression,
including arithmetic operators:

\beforeverb
\begin{verbatim}
let x = sin (degrees /. 360.0 *. 2 *. pi);;
\end{verbatim}
\afterverb
%
And even function calls:t

\beforeverb
\begin{verbatim}
let x = exp (log (x+.1.));;
\end{verbatim}
\afterverb
%
Note in this example that we put parentheses around the inner function and the inner 
expression, to tell OCaml how to read this statement. If we just told it \verb"exp log x+1;;" it would try to pass both {\tt log} and {\tt x} as two separate arguments 
to {\tt exp} and then add one.

Almost anywhere you can put a value, you can put an arbitrary
expression, with one exception: the left side of an assignment
statement has to be a variable name, or function definition, which
you'll see in the next section.  Any other expression on the left
side is a syntax error.

\beforeverb
\begin{verbatim}
 # let minutes = hours *. 60.0;;                 (* right *)
 # let hours *. 60 = minutes;;;                  (* wrong! *)
Error: Syntax error
\end{verbatim}
\afterverb
%
\index{SyntaxError}
\index{exception!SyntaxError}


\section{Adding new functions}

So far, we have only been using the functions that come with OCaml,
but it is also possible to add new functions.
A {\bf function definition} specifies the name of a new function and
the sequence of statements that execute when the function is called.

\index{function}
\index{function definition}
\index{definition!function}

Here is an example:
%edit here

\beforeverb
\begin{verbatim}
let  print_lyrics () = 
    print_string "I'm a lumberjack, and I'm okay. \n";
    print_string "I sleep all night and I work all day. \n";;
\end{verbatim}
\afterverb
%
Note that we use the "let" keyord to define functions just the same as
variables. The name of the function is \verb"print_lyrics".  The
rules for function names are the same as for variable names: letters,
numbers and some punctuation marks are legal, but the first character
can't be a number.  You can't use a keyword as the name of a function,
and you should avoid having a variable and a function with the same
name.

\index{argument}

The empty parentheses after the name indicate that this function
doesn't take any meaningful arguments. More specifically, it takes a unit type
argument, meaning when we call it we have to put empty parentheses after it.
If we don't put the parentheses, then it gives us a little information about
the function:

\beforeverb
\begin{verbatim}
# print_lyrics;;
- : unit -> unit = <fun>
\end{verbatim}
\afterverb
What this output means is that this is a function (\verb" = <fun>") which takes
a unit type argument and returns a unit (\verb"unit -> unit"). We'll see why this
is useful later.

But wait! Was that a single semi-colon I saw there? What was that? I thought
you used two semi-colons to end a statement? Well, sure, two semi-colons do
end a statement. But if you put two semi-colons inside a function definition, 
that ends the entire function definiton. So if we want a function to execute
one statement and then execute another statement, we terminate all the intermediate
statements with single semi-colons, which is called a {\em sequence point}. \footnote{
The sequence point is actually an operator, like +. It takes a unit on the 
left and anything on the right and returns the right.}
If we don't, we get an interesting syntax error:

\beforeverb
\begin{verbatim}
# let print_lyrics () = 
	print_string "I'm a lumberjack and I'm okay. \n"
	print_string "I work all night and I sleep all day. \n";;
Error: This function is applied to too many arguments;
maybe you forgot a `;'
\end{verbatim}
\afterverb
It's trying to treat the second \verb"print_string" as another argument in the first \verb"print_string"!
That's because we didn't give it anything to tell it that we've stopped putting in arguments
to the first \verb"print_string". In OCaml, a new line in code is nothing more than a space.
New lines and indentation just make your code easier to read and more organized. It doesn't
help the  OCaml compiler at all.

\index{parentheses!empty}
\index{type!unit}
\index{unit type}
\index{header}
\index{body}

The syntax for calling the new function is the same as for built-in functions:

\beforeverb
\begin{verbatim}
# print_lyrics();;
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
- : unit = ()
\end{verbatim}
\afterverb
%
Once you have defined a function, you can use it inside another
function.  For example, to repeat the previous refrain, we could write
a function called \verb"repeat_lyrics":

\beforeverb
\begin{verbatim}
let repeat_lyrics() = 
    print_lyrics();
    print_lyrics();;
\end{verbatim}
\afterverb
%
And then call \verb"repeat_lyrics();;":

\beforeverb
\begin{verbatim}
# repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
- : unit = ()
\end{verbatim}
\afterverb
%
But that's not really how the song goes.


\section{Definitions and uses}
\index{function definition}

Pulling together the code fragments from the previous section, the
whole program looks like this:

\beforeverb
\begin{verbatim}
let print_lyrics() =
    print_string "I'm a lumberjack, and I'm okay. \n";
    print_string "I sleep all night and I work all day. \n";;

let repeat_lyrics() =
    print_lyrics();
    print_lyrics();;

repeat_lyrics()
\end{verbatim}
\afterverb
%
This program contains two function definitions: \verb"print_lyrics" and
\verb"repeat_lyrics".  Function definitions get executed just like other
statements, but the effect is to create functions.  The statements
inside the function do not get executed until the function is called, and
the function definition generates only trivial output.

In OCaml, so you can define a function after you call it, so long as it is 
called and defined in the same script.

\begin{ex}
Move the last line of this program
to the top, so the function call appears before the definitions. Run 
the program and see if the output changes.
\end{ex}

\begin{ex}
Move the function call back to the bottom
and move the definition of \verb"print_lyrics" after the definition of
\verb"repeat_lyrics".  What happens when you run this program?
\end{ex}


\section{Flow of execution}
\index{flow of execution}

Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.

Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.

A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of
the function, executes all the statements there, and then comes back
to pick up where it left off.

That sounds simple enough, until you remember that one function can
call another.  While in the middle of one function, the program might
have to execute the statements in another function. But while
executing that new function, the program might have to execute yet
another function!

Fortunately, OCaml is good at keeping track of where it is, so each
time a function completes, the program picks up where it left off in
the function that called it.  When it gets to the end of the program,
it terminates.

What's the moral of this sordid tale?  When you read a program, you
don't always want to read from top to bottom.  Sometimes it makes
more sense if you follow the flow of execution.


\section{Parameters and arguments}
\label{parameters}
\index{parameter}
\index{function parameter}
\index{argument}
\index{function argument}

Some of the built-in functions we have seen require arguments.  For
example, when you call {\tt sin} you pass a floating-point
as an argument.  Some functions take more than one argument.

Inside the function, the arguments are assigned to
variables called {\bf parameters}.  Here is an example of a
user-defined function that takes an argument:

\index{parentheses!parameters in}

\beforeverb
\begin{verbatim}
let print_twice bruce =
	print_int bruce;
	print_string " ";
	print_int bruce;
	print_string "\n";;
\end{verbatim}
\afterverb
%
This function assigns the argument to a parameter
named {\tt bruce}.  When the function is called, it prints the value of
the parameter (which must be an integer) twice, with a space in between then
followed by a new line.

The same rules of composition that apply to built-in functions also
apply to user-defined functions, so we can use any kind of expression
as an argument for \verb"print_twice", so long as it evaluates to an integer:

\index{composition}

\beforeverb
\begin{verbatim}
>>> print_twice (3*4)
12 12
- : unit = ()
>>> print_twice (2+10)
12 12
- : unit = ()
\end{verbatim}
\afterverb
%
Note that we need to tell OCaml exactly what the argument is using parentheses in this case.
This is because if we omitted them it would read left to right, so the first function call 
would become {\tt (\verb"print_twice" 3)*4}, which doesn't make any sense, especially since
{\tt (\verb"print_twice" 3)} evaluates to a unit, which you can't really multiply by four.

The argument is evaluated before the function is called, so
in the examples the expressions {\tt 3*4} and
{\tt 2+10} are only evaluated once.

\index{argument}

You can also use a variable as an argument:

\beforeverb
\begin{verbatim}
>>> michael = 1
>>> print_twice michael
1 1
- : unit = ()
\end{verbatim}
\afterverb
%
The name of the variable we pass as an argument ({\tt michael}) has
nothing to do with the name of the parameter ({\tt bruce}).  It
doesn't matter what the value was called back home (in the caller);
here in \verb"print_twice", we call everybody {\tt bruce}.

\index{Higher-Order Functions}
\index{HOF}

Functions can also take other functions as arguments. Such a function
is called a {\em Higher-Order Function}, which is sometimes abbreviated HOF.


\section{Functions are Just Renamed Expressions}

In OCaml, functions are really just expressions renamed. This means that an 
Ocaml function must evaluate to a value, hence why you must use sequence points 
within a function definition.

Using {\tt let} within a function definition requires the in keyword:

\index{concatenation}

\beforeverb
\begin{verbatim}
let cat_twice part1 part2 = 
    let cat = part1^part2^"\n" in cat^cat;;
\end{verbatim}
\afterverb
This function takes two string arguments, concatenates them and adds a newline character, 
and then concatenates the result to itself and returns this string. Note that ``in'' in there: that's
so that the variable definition doesn't return anything itself; it's only part of an expression which
returns the result.

\section{Scope and Functions}
\index{local variable}
\index{variable!local}


\beforeverb
\begin{verbatim}
# let line1 = 'Bing tiddle ';;
# let line2 = 'tiddle bang.';;
# cat_twice line1 line2;;
Bing tiddle tiddle bang.
- : unit = ()
\end{verbatim}
\afterverb

When \verb"cat_twice" terminates, the variable {\tt cat}
is destroyed.  If we try to print it, we get an exception:

\beforeverb
\begin{verbatim}
# print_string cat
Error: Unbound value cat
\end{verbatim}
\afterverb

Parameters are also local.
For example, outside \verb"_twice", there is no
such thing as {\tt bruce}.

\index{parameter}


\section{Stack diagrams}
\label{stackdiagram}
\index{stack diagram}
\index{function frame}
\index{frame}
%edit here like a mofo!
To keep track of which variables can be used where, it is sometimes 
useful to draw a {\bf stack diagram}.  Like state diagrams, stack 
diagrams show the value of each variable, but they also show the 
function each variable belongs to.

\index{stack diagram}
\index{diagram!stack}

Each function is represented by a {\bf frame}.  A frame is a box
with the name of a function
beside it and the parameters and variables of the function inside it.
The stack diagram for the
previous example looks like this:

\beforefig
\centerline{\includegraphics{figs/stack.eps}}
\afterfig

The frames are arranged in a stack that indicates which function
called which, and so on.  In this example, \verb"print_twice"
was called by \verb"cat_twice", and \verb"cat_twice" was called by 
\verb"__main__", which is a special name for the topmost frame.  When
you create a variable outside of any function, it belongs to 
\verb"__main__".

Each parameter refers to the same value as its corresponding
argument.  So, {\tt part1} has the same value as
{\tt line1}, {\tt part2} has the same value as {\tt line2},
and {\tt bruce} has the same value as {\tt cat}.

\section{Currying Functions}

\index{Currying}
\index{Functions!Currying}

Currying functions is a very odd, but very powerful, idea in OCaml.

You've probably noticed that OCaml gives you a very interesting output
after a function definition. Consider the following (somewhat trivial) function:

\beforeverb
\begin{verbatim}
# let add a b = a+b;;
val add: int -> int -> int = <fun>
\end{verbatim}
\afterverb

Effectively, what this means is that you have a function which takes two 
integers as input and returns an integer (in this case, the sum of the two). 
What's with the arrows, then? Well, this syntax was chosen for a reason.

Consider the following:

\beforeverb
\begin{verbatim}
# add 3;;
\end{verbatim}
\afterverb

What is that? If you're familiar with other programming languages, you might 
assume it's a syntax error: the function doesn't have enough input arguments!
Well, you would be wrong. In fact, there's no error at all. That is a perfectly
valid statement in OCaml:

\beforeverb
\begin{verbatim}
# add 3;;
- : int -> int = <fun>
\end{verbatim}
\afterverb

That's right, {\tt add 3} is actually a function in it's own right. It takes an integer
as an input, to which it will add three and then return the result. That's because functions
of multiple input arguments in OCaml are really just chains of single-argument functions. 
Hence, {\tt add a b} is really the function {\tt add a} applied to {\tt b}, which is really 
the function {\tt add} applied to {\tt a}, the result of which is then applied to {\tt b}. 
\footnote{If you've never heard of currying before and that made sense to you the first 
time through, then you deserve a medal and you're going to love when we get to recursion.} 
This is called `{\bf currying}, after Haskell Curry. It is also sometimes called 
{\bf partial application}.

\index{Partial Application}

In fact, we can even name this function:

\beforeverb
\begin{verbatim}
# let add3 = add 3;;
val add3 : int -> int = <fun>
# add3 2;;
- : int = 5
\end{verbatim}
\afterverb

This would be effectively the same as writing:

\beforeverb
\begin{verbatim}
# let add3 b = add 3 b;;
val add3 : int -> int = <fun>
# add3 2;;
- : int = 5
\end{verbatim}
\afterverb
%
Except the first one is a little cleaner. In this trivial example, the difference is
very slight, but when we introduce some new concepts later, you'll see why currying
is so powerful.

\section{Why functions?}
\index{function, reasons for}

It may not be clear why it is worth the trouble to divide
a program into functions.  There are several reasons:

\begin{itemize}

\item Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read and debug.

\item Functions can make a program smaller by eliminating repetitive
code.  Later, if you make a change, you only have
to make it in one place.

\item Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working whole.

\item Well-designed functions are often useful for many programs.
Once you write and debug one, you can reuse it.

\end{itemize}

\section{Debugging}
\label{editor}
\index{debugging}

Don't forget to save your program before you run it.  Some
development environments do this automatically, but some don't.
In that case the program you are looking at in the text editor
is not the same as the program you are running.

Debugging can take a long time if you keep running the same,
incorrect, program over and over!

Make sure that the code you are looking at is the code you are running.
If you're not sure, put something like {\tt print\_int 42} at the
beginning of the program and run it again.  If you don't see
{\tt 42}, you're not running the right program!


\section{Glossary}

\begin{description}

\item[function:] A named sequence of statements that performs some
useful operation.  Functions may take any parameter and return any 
type, including the unit type.
\index{function}

\item[function definition:]  A statement that creates a new function,
specifying its name, parameters, and the statements it executes.
\index{function definition}

\item[function object:]  A value created by a function definition.
The name of the function is a variable that refers to a function
object.
\index{function definition}

\item[header:] The first line of a function definition.
\index{header}

\item[body:] The sequence of statements inside a function definition.
\index{body}

\item[parameter:] A name used inside a function to refer to the value
passed as an argument.
\index{parameter}

\item[function call:] A statement that executes a function. It
consists of the function name followed by an argument list.
\index{function call}

\item[argument:]  A value provided to a function when the function is called.
This value is assigned to the corresponding parameter in the function.
\index{argument}

\item[local variable:]  A variable defined inside a function.  A local
variable can only be used inside its function.
\index{local variable}

\item[return value:]  The result of a function.  If a function call
is used as an expression, the return value is the value of
the expression.
\index{return value}

%\item[fruitful function:] A function that returns a value.
%\index{fruitful function}

%\item[void function:] A function that doesn't return a value.
%\index{void function}

\item[module:] A file that contains a
collection of related functions and other definitions.
\index{module}

%\item[import statement:] A statement that reads a module file and creates
%a module object.
%\index{import statement}
%\index{statement!import}

%\item[module object:] A value created by an {\tt import} statement
%that provides access to the values defined in a module.
%\index{module}

\item[dot notation:]  The syntax for calling a function in another
module by specifying the module name followed by a dot (period) and
the function name.
\index{dot notation}

\item[composition:] Using an expression as part of a larger expression,
or a statement as part of a larger statement.
\index{composition}

\item[flow of execution:]  The order in which statements are executed during
a program run.
\index{flow of execution}

%\item[stack diagram:]  A graphical representation of a stack of functions,
%their variables, and the values they refer to.
%\index{stack diagram}

%\item[frame:]  A box in a stack diagram that represents a function call.
%It contains the local variables and parameters of the function.
%\index{function frame}
%\index{frame}

%\item[traceback:]  A list of the functions that are executing,
%printed when an exception occurs.
%\index{traceback}

\item[currying:] Also known as partial application. The use of a function
such that, instead of having multiple arguments, it is instead a chain of 
single-argument functions.

\end{description}


\section{Exercises}

% \begin{ex}
% 
% \index{len function}
% \index{function!len}
% 
% OCaml provides a standard module called {\tt String}, which includes a useful 
% function called {\tt length } that returns the length of a string, so the value 
% of \begin{verbatim} String.length("monje")" \end{verbatim} is 5.
% 
% Write a function named \verb"right_justify" that takes a string
% named {\tt s} as a parameter and prints the string with enough
% leading spaces so that the last letter of the string is in column 70
% of the display.
% 
% \beforeverb
% \begin{verbatim}
% # right_justify('monje')
%                                                                  monje
% \end{verbatim}
% \afterverb
% 
% \end{ex}
% 
\begin{ex}
Write a function that takes two strings as an argument and concatenates
them with a space in between.

Now use currying with that function to define functions that append + and - 
to the end of the string, again with a space in between.

Finally, write a function to append a symbol x number of times.

\end{ex}

% \begin{ex}
% This exercise\footnote{Based on an exercise in Oualline, {\em
%     Practical C Programming, Third Edition}, O'Reilly (1997)} can be
% done using only the statements and other features we have learned so
% far.
% 
% \index{grid}
% 
% \begin{enumerate}
% 
% \item Write a function that draws a grid like the
%   following:
% 
% \beforeverb
% \begin{verbatim}
% + - - - - + - - - - +
% |         |         |
% |         |         |
% |         |         |
% |         |         |
% + - - - - + - - - - +
% |         |         |
% |         |         |
% |         |         |
% |         |         |
% + - - - - + - - - - +
% \end{verbatim}
% \afterverb
% 
% 
% \item Use the previous function to draw a similar grid
% with four rows and four columns.
% 
% \end{enumerate}

%You can see my solution at \url{thinkpython.com/ocaml/code/grid.ml}.
%% Not yet you can't!
\end{ex}

%%removed chapter using TurtleWorld. Would love to write suitable replacement.

\chapter{Program Flow}

\section{Modulus operator}

\index{modulus operator}
\index{operator!modulus}

The {\bf modulus operator} works on integers and yields the remainder
when the first operand is divided by the second.  In OCaml, the
modulus operator is {\tt mod}. The syntax is the same
as for other operators:

\beforeverb
\begin{verbatim}
# let quotient = 7 / 3;;
val quotient : int = 2
# let remainder = 7 mod 3;;
val remainder : int = 1
\end{verbatim}
\afterverb
%
So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful.  For
example, you can check whether one number is divisible by another---if
{\tt x mod y} is zero, then {\tt x} is divisible by {\tt y}.

\index{divisibility}

Also, you can extract the right-most digit
or digits from a number.  For example, {\tt x mod 10} yields the
right-most digit of {\tt x} (in base 10).  Similarly {\tt x mod 100}
yields the last two digits.


\section{Boolean expressions}
\index{boolean expression}
\index{expression!boolean}
\index{logical operator}
\index{operator!logical}

A {\bf boolean expression} is an expression that is either true
or false.  The following examples use the 
operator {\tt <>}, which compares two operands and produces
{\tt false} if they are equal and {\tt true} if they are:

\beforeverb
\begin{verbatim}
>>> 5 <> 5;;
- : bool = false
>>> 5 <> 6;;
- : bool = true
\end{verbatim}
\afterverb
%
{\tt True} and {\tt False} are special
values that belong to the type {\tt bool}; they are not strings.

The {\tt <>} operator is one of the {\bf relational operators}; the
others are:

\beforeverb
\begin{verbatim}
      x <> y               # x is not equal to y
      x > y                # x is greater than y
      x < y                # x is less than y
      x >= y               # x is greater than or equal to y
      x <= y               # x is less than or equal to y
\end{verbatim}
\afterverb
%
Although these operations are probably familiar to you, the OCaml
symbols are different from the mathematical symbols.



\index{relational operator}
\index{operator!relational}


\section {Logical operators}
\index{logical operator}
\index{operator!logical}

There are three {\bf logical operators}: {\tt \verb"&&"} (and), {\tt
\verb"||"} (or), and {\tt not} (exactly as it looks).  The semantics (meaning) of these operators is
similar to their meaning in English.  For example,
{\tt x > 0 \verb"&&" x < 10} is true only if {\tt x} is greater than 0
{\em and} less than 10.

\index{and operator}
\index{or operator}
\index{not operator}
\index{operator!and}
\index{operator!or}
\index{operator!not}

{\tt n mod 2 = 0 || n mod 3 = 0} is true if {\em either} of the conditions
is true, that is, if the number is divisible by 2 {\em or} 3.

Finally, the {\tt not} operator negates a boolean
expression, so {\tt not (x > y)} is true if {\tt x > y} is false,
that is, if {\tt x} is less than or equal to {\tt y}.

\section{Conditional execution}
\label{conditional execution}

\index{conditional statement}
\index{statement!conditional}
\index{if statement}
\index{statement!if}
\index{conditional execution}

In order to write useful programs, we almost always need the ability
to check conditions and change the behavior of the program
accordingly.  {\bf Conditional statements} give us this ability.  The
simplest form is the {\tt if} statement:

\beforeverb
\begin{verbatim}
if x > 0
then print_string "x is positive."
else print_string "x is not certain.";;
\end{verbatim}
\afterverb

The boolean expression after the {\tt if} statement is
called the {\bf condition}.  If it is true, then the expression 
after {\tt then} gets executed.  If not, then the {\tt else} expression 
is evaluated. The only caveat is that the {\tt then} and {\tt else} expressions
must evaluate to values of the same type, both integers for example.

The else expression can be omitted, in which case it defaults
to {\tt else ()}. This can be problematic as it means the {\tt then} clause must
also evaluate to the unit type.

As with most things in OCaml, as you're probably beginning to notice, the 
then-expression and else-expression must evaluate to one value (i.e., be expressions).
Sometimes, though, you might want to do more than one thing within those expressions.
For example, you might want to display the value of something. For just that, we have 
{\tt begin} and {\tt end}.

\beforeverb
\begin{verbatim}
if x>0
then begin
          print_int x;
          x
     end
else x+1;;
\end{verbatim}
\afterverb

Note that the first line within the {\tt begin...end} block is followed by a sequence point:
anything returned by the first line will just be discarded. However, it's considered good form
for it to always return the unit, and it will spew warning errors at you if it returns anything
else.

\section{Chained conditionals}
\index{chained conditional}
\index{conditional!chained}

Sometimes there are more than two possibilities and we need more than
two branches.  One way to express a computation like that is a {\bf
chained conditional}:

\beforeverb
\begin{verbatim}
if x > 3
then "x is big."
else if x = 3:
     then "x is three."
else "x is little.";;
\end{verbatim}
\afterverb
%
There is no limit on the number of {\tt else if} statements. However, these
trees become harder to correctly interpret the more branches you put on, and
the code can get very unmanagable. We'll see better ways to control program 
flow as we go along.

\beforeverb
\begin{verbatim}
if choice = 'a':
then draw_a()
else if choice = 'b':
     then draw_b()
else if choice = 'c':
    then draw_c()
\end{verbatim}
\afterverb
%
Each condition is checked in order.  If the first is false,
the next is checked, and so on.  If one of them is
true, the corresponding branch executes, and the statement
ends.  Even if more than one condition is true, only the
first true branch executes.

\index{nested conditional}
Because one conditional is within the body of another conditional,
it is referred to as a {\bf nested conditional}. Nested conditionals
can also occur within the {\tt then} clauses of if statements.

\beforeverb
\begin{verbatim}
if 0 < x
then if x < 10
print_string "x is a positive single-digit number."
\end{verbatim}
\afterverb

Logical operators often provide a way to simplify nested conditional
statements.  For example, we can rewrite the above code using a
single conditional:

\beforeverb
\begin{verbatim}
if 0<x && x<10
then print_string "x is a positive single-digit number."
\end{verbatim}
\afterverb

\section{Keyboard input}
\index{keyboard input}

The programs we have written so far are a bit rude in the sense that
they accept no input from the user.  They just do the same thing every
time.

OCaml provides three built-in functions that get input from the keyboard, 
one each for getting strings, floats, and ints. They are, respectively, 
named {\tt \verb"read_line"}, {\tt \verb"read_float"}, and {\tt \verb"read_int"}, and all take
a unit argument. When one of these functions is called, the program stops 
and waits for the user to type something.  When the user presses {\sf Return} 
or {\sf Enter}, the program resumes with the collected value.

\index{User input}
\index{Read functions}

\beforeverb
\begin{verbatim}
# let input = read_line ();;
What are you waiting for?
# print_string input;;
What are you waiting for?
\end{verbatim}
\afterverb
%
Before getting input from the user, it is a good idea to print a
prompt telling the user what to input.

\index{prompt}

\beforeverb
\begin{verbatim}
print_string "What...is your name?\n";;
let input = read_line();;
\end{verbatim}
\afterverb
%
You can then do something with the user's input. For example, we could have
the program greet the user:

\beforeverb
\begin{verbatim}
let greet () = print_string "What...is your name?\n";
	let input = read_line() in
	let greeting = "Hi "^input^"\n" in
	print_string greeting;;
\end{verbatim}
\afterverb

This could result in the following execution:

\beforeverb
\begin{verbatim}
# greet ();;
What... is your name?
Monje
Hi Monje
- : unit = ()
\end{verbatim}
\afterverb
where the second line is user input.

\section{Pattern Matching}
\index{Pattern Matching}

One of the coolest features of OCaml is it's ability to 
take some object (string, integer, anything) and match 
it with user-determined patterns and respond accordingly. 
This allows us to do all kinds of things, from making 
conditionals more complicated than {\tt if... then... else} 
without incessant nesting, to parsing text. We'll look at 
complicated examples later, but for now let's look at the
syntax in the abstract:

\beforeverb
\begin{verbatim}
match object with
	pattern a -> result a
	| pattern b -> result b
	| pattern c -> result c
	...
\end{verbatim}
\afterverb

The object can be absolutely anything. The pattern is something
of the same type as the object, or an expression that evaluates to 
the same type. Note that the order is significant - OCaml will take 
the result of the first match, not necessarily the best one, though 
generally we want cases to be mutually exclusive.

The pattern needing to be the same type as the object turns out to 
be something of a limitation. What if we wanted to determine the sign 
of an integer? We could use if statements, but we really have three 
possibilities - negative, 0, and positive - and nesting 
if statements is just so ugly and hard to follow.

We might start to write a pattern like this:

\beforeverb
\begin{verbatim}
let sign i = match i with 
	0 -> 0
	| x -> 1 (* this will match all integers! *)
\end{verbatim}
\afterverb

This example will compile, but it won't do what you want it to do.
The {\tt x} case will match all integers! We need to be able to 
distinguish between positive and negative integers. In order to do this,
we want to {\bf guard} these patterns. This means we use {\tt when} to 
impose a condition on the pattern, like so:
\index{Pattern-Matching!Guarded}
\index{Guarded Patterns}

\beforeverb
\begin{verbatim}
let sign i = match i with
	x when x < 0 -> -1
	| 0 -> 0
	| x -> 1;;
\end{verbatim}
\afterverb

Note that the last line is not guarded even though we don't want all 
integers to return one. However, we have already eliminated all the 
cases we don't want to return one, so there's really no point in guarding
this case. It will simply make it longer and harder to read. Additionally,
if all patterns in a pattern-matching are guarded, you'll get a warning 
message telling you it's bad style.

You can also tell OCaml to match with anything using an \verb"_", and you
can use the {\tt as} keyword to rename a pattern. The following example is
silly, but demonstrates both of these abilities:

\beforeverb
\begin{verbatim}
let add3 i = match i with
	(_ as x) -> x+3;;
\end{verbatim}
\afterverb

The underscore will match anything that fits within the pattern. The {\tt 
as} lets us call whatever we matched there {\tt x} and then use it in the
result side.

We'll see lots more awesome examples of pattern matching as we go along.

\section{Glossary}
\begin{description}

\item[modulus operator:]  An operator, denoted with a percent sign
({\tt \%}), that works on integers and yields the remainder when one
number is divided by another.
\index{modulus operator}
\index{operator!modulus}

\item[boolean expression:]  An expression whose value is either 
{\tt true} or {\tt false}.
\index{boolean expression}
\index{expression!boolean}

\item[relational operator:] One of the operators that compares
its operands: {\tt =}, {\tt <>}, {\tt >}, {\tt <}, {\tt >=}, and {\tt <=}.

\item[logical operator:] One of the operators that combines boolean
expressions: {\tt and}, {\tt or}, and {\tt not}.

\item[conditional statement:]  A statement that controls the flow of
execution depending on some condition.
\index{conditional statement}
\index{statement!conditional}

\item[condition:] The boolean expression in a conditional statement
that determines which branch is executed.
\index{condition}

\item[compound statement:]  A statement that consists of a header
and a body.  The header ends with a colon (:).  The body is indented
relative to the header.
\index{compound statement}

\item[body:] The sequence of statements within a compound statement.
\index{body}

\item[branch:] One of the alternative sequences of statements in
a conditional statement.
\index{branch}

\item[nested conditional:]  A conditional statement that appears
in one of the branches of another conditional statement.
\index{nested conditional}
\index{conditional!nested}

\end{description}

\section{Exercises}

\begin{ex}
\index{Fermat's Last Theorem}

Fermat's Last Theorem says that there are no integers
$a$, $b$, and $c$ such that

\[ a^n + b^n = c^n \]
%
for any values of $n$ greater than 2.

\begin{enumerate}

\item Write a function named \verb"check_fermat" that takes four
parameters---{\tt a}, {\tt b}, {\tt c} and {\tt n}---and
that checks to see if Fermat's theorem holds.  If
$n$ is greater than 2 and it turns out to be true that 

\[a^n + b^n = c^n \]
%
the program should print, ``Holy smokes, Fermat was wrong!''
Otherwise the program should print, ``No, that doesn't work.''

\item Write a function that prompts the user to input values
for {\tt a}, {\tt b}, {\tt c} and {\tt n}, converts them to
integers, and uses \verb"check_fermat" to check whether they
violate Fermat's theorem.

\end{enumerate}

\end{ex}


\begin{ex}
\index{triangle}

If you are given three sticks, you may or may not be able to arrange
them in a triangle.  For example, if one of the sticks is 12 inches
long and the other two are one inch long, it is clear that you will
not be able to get the short sticks to meet in the middle.  For any
three lengths, there is a simple test to see if it is possible to form
a triangle:

\begin{quotation}
``If any of the three lengths is greater than the sum of the other
  two, then you cannot form a triangle.  Otherwise, you
  can\footnote{If the sum of two lengths equals the third, they form
    what is called a ``degenerate'' triangle.}.''
\end{quotation}

\begin{enumerate}

\item Write a function named \verb"is_triangle" that takes three
  integers as arguments, and that prints either ``Yes'' or ``No,'' depending
  on whether you can or cannot form a triangle from sticks with the
  given lengths.

\item Write a function that prompts the user to input three stick
  lengths, converts them to integers, and uses \verb"is_triangle" to
  check whether sticks with the given lengths can form a triangle.

\end{enumerate}

\end{ex}


\chapter{Recursive Functions}
\label{recursion}
\index{recursion}
\index{function!recursive}

In mathematics, a {\bf recursive function} has the general form:

\begin{equation*}
a_{n+1} = f(a_n,a_{n-1},a_{n-2}...)
\end{equation*}

meaning that the next term in the sequence $a$ is a function 
of previous terms in the sequence, generally just the last one. 
This process is called {\bf recursion}.Some recursive functions 
will be functions of more terms than just the last term. In 
computer science, this idea can be used for all kinds of 
important calculations, and can be much simpler than 
non-recursive solutions - such as loops, for example.

In both mathematics and computer science, you require two 
things: a base case, and a recursive step. The base case is 
usually the simplest possible case - often $n = 0$ - and the
recursive step gives the next term given the term before it.
Usually in programming, we don't know the term before it when 
we call for it, but we can calculate it in terms of the previous 
case - and so on and so on recursively until the base case. The 
recursive step can be thought of as ``wishful thinking'' - if I 
knew the $n^{th}$ case, then the ${n+1}^{th}$ case would be simple.

While usually we're looking for the $n^{th}$ case, it's often
helpful to first think of recursion in forward terms:

\begin{align*}
a_0 &&& \\
a_1 &= f(a_0) && \\
a_2 &= f(a_1) & = f(f(a_0)) &\\
a_3 &= f(a_2) & = f(f(a_1))) &= f(f(f(a_0))) \\
\end{align*}
and so on and so forth.

So you can see, the third term can be 
evaluated directly by applying $f$ to the second term, which is 
an application of $f$ to the first term, which is itself an 
application of $f$ to the base case.

If this doesn't make any sense right now, don't worry; recursion 
can be a hard concept to wrap your mind around at first. We'll get
through a few examples and maybe it will get a little clearer.

\section{Recursion}

It is legal for one function to call another; it is also legal 
for a function to call itself. However, to define a recursive
function in OCaml, you must tell the compiler you're going to
do this by using {\tt let rec} instead of just {\tt let}.
For example, look at the following function:

\beforeverb
\begin{verbatim}
let rec countdown n = 
	if n <= 0
	then (
		print_string "Blastoff!";
		print_newline())
	else (
		print_int n;
		print_newline();
		countdown (n-1); ());;
\end{verbatim}
\afterverb
%
If {\tt n} is 0 or negative, it outputs the word, ``Blastoff!''
Otherwise, it outputs {\tt n} and then calls a function named {\tt
countdown}---itself---passing {\tt n-1} as an argument. Note the else
block ends with a (), telling the compiler that it returns a unit.

What happens if we call this function like this?

\beforeverb
\begin{verbatim}
# countdown 3;;
\end{verbatim}
\afterverb
%
The execution of {\tt countdown} begins with {\tt n=3}, and since
{\tt n} is greater than 0, it outputs the value 3, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt n=2}, and since
{\tt n} is greater than 0, it outputs the value 2, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt n=1}, and since
{\tt n} is greater than 0, it outputs the value 1, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt n=0}, and since {\tt
n} is not greater than 0, it outputs the word, ``Blastoff!'' and then
returns.
\end{quote}

The {\tt countdown} that got {\tt n=1} returns.
\end{quote}

The {\tt countdown} that got {\tt n=2} returns.
\end{quote}

The {\tt countdown} that got {\tt n=3} returns.

And then you're back in \verb"__main__".  So, the
total output looks like this:

\beforeverb
\begin{verbatim}
3
2
1
Blastoff!
- : unit = ()
\end{verbatim}
\afterverb
%

As another example, we can write a function that prints a
string {\tt n} times.

\beforeverb
\begin{verbatim}
let rec print_n n s = 
    if n <= 0
    then ()
    else (
	print_string s;
	print_newline();
	print_n (n-1) s;
	());;
\end{verbatim}
\afterverb
%
If {\tt n <= 0} the function simply returns a unit. The
flow of execution immediately returns to the caller.

The rest of the function is similar to {\tt countdown}: if {\tt n} is
greater than 0, it displays {\tt s} and then calls itself to display
{\tt s} $n-1$ additional times.  So the number of lines of output
is {\tt 1 + (n - 1)}, which adds up to {\tt n}.

Now, this is all fun and games, but we can also use recursive functions
to do real work, and return an actual value.

Let's say we wanted to add up all the integers from one to some integer n. Of course, 
we could use the simple analytic solution, but that would be silly.\footnote{No, it 
wouldn't be silly. If you have a convenient analytic solution, use it, it's probably 
more efficient, but for the sake of pedagogy, let's go ahead and not use the analytic 
solution.} A recursive solution to this problem might look like this:

\beforeverb
\begin{verbatim}
let rec csum n = 
	if n = 0
	then 0
	else (n + csum (n-1));;
\end{verbatim}
\afterverb

\begin{ex}
OCaml wil also trace a recursive function for you (or any function, really).

Type {\tt \verb"#trace" csum} into the interpreter and call {\tt csum 3}. See if you 
can interpret the result. Play around with this feature for some other functions
to make sure you really understand what it's printing out.
\end{ex}


%\section{Stack diagrams for recursive functions}
%\index{stack diagram}
%\index{function frame}
%\index{frame}

%In Section~\ref{stackdiagram}, we used a stack diagram to represent
%the state of a program during a function call.  The same kind of
%diagram can help interpret a recursive function.

%Every time a function gets called, OCaml creates a new function
%frame, which contains the function's local variables and parameters.
%For a recursive function, there might be more than one frame on the
%stack at the same time.

%This figure shows a stack diagram for {\tt countdown} called with
%{\tt n = 3}:

%\beforefig
%\centerline{\includegraphics{figs/stack2.eps}}
%\afterfig

%\index{base case}
%\index{recursion!base case}

%The four {\tt countdown} frames have different values for the
%parameter {\tt n}.  The bottom of the stack, where {\tt n=0}, is
%called the {\bf base case}.  It does not make a recursive call, so
%there are no more frames.

%\begin{ex}
%Draw a stack diagram for \verb"print_n" called with
%\verb"s = 'Hello'" and {\tt n=2}.
%\end{ex}

\section{Infinite recursion}
\index{infinite recursion}
\index{recursion!infinite}
\index{runtime error}
\index{error!runtime}
\index{traceback}

If a recursion never reaches a base case, it goes on making
recursive calls forever, and the program never terminates.  This is
known as {\bf infinite recursion}, and it is generally not
a good idea.  The most common source of infinite recursion
is forgetting to decrement when you make the recursive call:

\beforeverb
\begin{verbatim}
let rec csum n = 
	if n = 0
	then 0
	else (n + csum n);;
\end{verbatim}
\afterverb
%
In most programming environments, a program with infinite recursion
does not really run forever. Usually, you run out of what they call
``stack space'', which is a function of your computer architecture.

\index{exception!RuntimeError}
\index{RuntimeError}

\beforeverb
\begin{verbatim}
# csum 10;;
Stack overflow during evaluation (looping recursion?).
\end{verbatim}
\afterverb

The error can also occur if the program doesn't reach the base case
for any reason. {\tt csum}, for example, isn't particularly robust:
if we give it a negative number, it explodes.

\beforeverb
\begin{verbatim}
# csum (-2);;
Stack overflow during evaluation (looping recursion?).
\end{verbatim}
\afterverb

{\tt csum} will continue subtracting from $-2$ ad infinitum without 
ever reaching 0, so it will keep going until it runs out of space.
This could be easily avoided by checking to make sure the argument 
is non-negative.

\section{Mutually Recursive Functions}

It's not really that common, but every once in a while you might want
to define recursive functions that call each other. Here's a trivial 
example:\footnote{Thanks to Ryan Tarpine who submitted it to 
ocaml-tutorial.org} 0 is an even number, and a number is defined as 
even if its predecessor is odd. Naturally, we could easily just check
{\tt x mod 2} to see if x is even, but that wouldn't be pedagogically
as interesting as this:

\beforeverb
\begin{verbatim}
let rec even x = 
	if x = 0
	then true
	else odd (x-1);;
let rec odd x = 
	if x = 0
	then false
	else even (x-1);;
\end{verbatim}
\afterverb

Not the prettiest solution, but it should work, right? Well, actually, no.
Because of how OCaml compiles, it would need odd first to compile even, but
would also need even first to compile odd. Somehow we need to tell OCaml to
compile both functions at the same time. Fortunately, OCaml comes with a 
syntax to do this:

\beforeverb
\begin{verbatim}
let rec even x = 
	if x = 0
	then true
	else odd (x-1)
and odd x = 
	if x = 0
	then false
	else even (x-1);;
\end{verbatim}
\afterverb

\section{Tail-end Recursion}

\index{Tail-end Recursion}
\index{Recursion!Tail-end}

Remember {\tt csum}? Well, it looked like this:

\beforeverb
\begin{verbatim}
let rec csum n = 
	if n=1
	then 1
	else n + (csum (n-1));;
\end{verbatim}
\afterverb

This is a perfectly valid, and reasonably efficient solution to this
problem, and the code is very easy to follow. However, there's one 
problem with this code: as n increases, we make proportionally more 
function calls to csum, each of which takes up a little bit of memory.
For most situations, this is probably fine, and certainly in this case,
we'd have to give it a relatively huge integer for most modern computers 
to run out of memory. However, for other programs, we might want to be 
able to write recursive functions that don't build up on that stack. But 
how can we do that?

The answer is called {\bf tail-end recursion}. The general idea is to write
your recursive function such that the value returned by the recursive call 
is what's returned by your function, i.e., there's no pending operation 
in the function waiting for the value returned by the recursive call. That 
way, the function can say, "Don't bother with me anymore, just take the answer 
from my recursive call as the result. You can just forget all of my state 
information."

Generally, in order to implement tail-end recursion we need an extra argument 
that accumulates the result along the way, so the inner-most recursive call
has all the information from the steps before it. Going back to our summing 
example, you might implement it like this:

\beforeverb
\begin{verbatim}
let rec csum_helper accum n = 
	if n=1
	then (accum+1)
	else (csum_helper (accum+n)) (n-1);;

let csum = csum_helper 0;;
\end{verbatim}
\afterverb.

Note how {\tt \verb"csum_helper"}'s return value is either the answer or simply the 
result of the recursive call. Hence, the computer does not need to keep this 
function around, it just needs to take the value from the recursive call. Also, 
note how I've arranged this program: because I needed an {\tt accum} argument, 
but when I call the function that will always be {\tt 0}, I've seperated this 
into two functions, a {\bf helper function} and a {\bf call function}. All the 
work happens in the helper function, but I don't want to have to tell it that
{\tt accum} is (in the first call) just zero every time I want to call the 
function, so I write another function to do that for me (which I defined using
currying!).

Tail-recursion is generally faster and requires less memory than standard recursion. 
However, it can be hard to see a tail-recursive solution the first time writing an 
algorithm, so it's often easier to write a standard recursion solution and then figure 
out a tail-recursive algorithm based on that code. Also, tail-recursive solutions are 
usually much less clear than standard recursion, so in cases where other people will be 
reading your code and you don't need to worry about the memory used, it's often better 
to just use standard recursion. Finally, there might not always be an obvious tail-recursive
solution and it might not be the best use of your time to find an algorithm if it won't 
significantly improve your code's performance.

Now, you may be wondering how computers know that this function is tail-recursive.
The answer is, they don't, but some compilers do. OCaml implements tail-recursion 
as a standard of the language, as do many other functional programming languages. 
However, many other programming languages, such as Python, do not implement 
tail-recursion. If you learn other programming languages later, make sure to find 
out whether or not they implement tail-recursion before using it, or else you'll 
gain nothing but harder-to-read code.

\section{Debugging}
\label{whitespace}
\index{debugging}
\index{traceback}
%edit here!
The traceback OCaml displays when an error occurs contains
a lot of information, but it can be overwhelming, especially
when there are many frames on the stack.  The most
useful parts are usually:

\begin{itemize}

\item What kind of error it was, and

\item Where it occurred.

\end{itemize}

In general, error messages indicate where the problem was
discovered, but the actual error might be earlier in the code,
sometimes on a previous line.

\section{Glossary}

\begin{description}

\item[recursion:]  The process of calling the function that is
currently executing.
\index{recursion}

\item[base case:]  A conditional branch in a
recursive function that does not make a recursive call.
\index{base case}

\item[infinite recursion:]  A recursive function that doesn't have a
base case, or never reaches it.  Eventually, an infinite recursion
causes a runtime error.
\index{infinite recursion}

\item[tail-end recursion:] A recursive function whose result is either 
the base case or the result of a recursive call, and hence does not have
an operation pending for the result of said recursive call.
\index{tail-end recursion}

\end{description}

\section{Exercises}

\begin{ex}
You've probably heard of the fibonacci numbers before, but in case you haven't, they're defined by the following recursive relationship: \footnote{Sometimes the specifics of the base cases looks a little different, but it all works out to be the same series.}

\begin{eqnarray*}
f(0) &=& 0 \\
f(1) &=& 1 \\
f(n+1) &=& f(n) + f(n-1)
\end{eqnarray*}

Write a recursive function to calculate these numbers. It does not need to be tail recursive.

\end{ex} \label{ex:fibonacci}

\begin{ex}
\index{Ackerman function}
\index{function!ack}

The Ackermann function, $A(m, n)$, is defined\footnote{See
  \url{wikipedia.org/wiki/Sometimes the specifics of the base cases looks a little different, but it all works out to be the same series.Ackermann_function}.}:

\begin{eqnarray}
A(m, n) = \begin{cases} 
              n+1 & \mbox{if } m = 0 \\ 
        A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\ 
A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.
\end{cases} 
\end{eqnarray}
%
Write a function named {\tt ack} that evaluates Ackerman's function.
Use your function to evaluate {\tt ack(3, 4)}, which should be 125.
What happens for larger values of {\tt m} and {\tt n}?

\end{ex}


\begin{ex}
\label{palindrome}

\index{palindrome}

A palindrome is a word that is spelled the same backward and
forward, like ``noon'' and ``redivider''.  Recursively, a word
is a palindrome if the first and last letters are the same
and the middle is a palindrome.

The following are functions that take a string argument and
return the first, last, and middle letters:

\beforeverb
\begin{verbatim}
let first_char word = word.[0];;

let last_char word =
	let len = String.length word - 1
	in word.[len];;

let middle word = 
	let len = String.length word - 2 in
	String.sub word 1 len;;
\end{verbatim}
\afterverb
%edit here
Note that these function use syntax you haven't seen yet. 
We'll see how they work in Chapter~\ref{strings}.

\begin{enumerate}

\item Type these functions into a file named {\tt palindrome.ml}
and test them out.  What happens if you call {\tt middle} with
a string with two letters?  One letter?  What about the empty
string, which is written \verb"''" and contains no letters?

\item Write a function called \verb"is_palindrome" that takes
a string argument and returns {\tt True} if it is a palindrome
and {\tt False} otherwise.  Remember that you can use the
built-in function {\tt len} to check the length of a string.

\end{enumerate}

\end{ex}

\begin{ex}
A number, $a$, is a power of $b$ if it is divisible by $b$
and $a/b$ is a power of $b$.  Write a function called
\verb"is_power" that takes parameters {\tt a} and {\tt b}
and returns {\tt True} if {\tt a} is a power of {\tt b}.
\end{ex}


\begin{ex}

\index{greatest common divisor (GCD)}
\index{GCD (greatest common divisor)}

The greatest common divisor (GCD) of $a$ and $b$ is the largest number
that divides both of them with no remainder\footnote{This exercise is
  based on an example from Abelson and Sussman's {\em Structure and
    Interpretation of Computer Programs}.}.

One way to find the GCD of two numbers is Euclid's algorithm,
which is based on the observation that if $r$ is the remainder
when $a$ is divided by $b$, then $gcd(a, b) = gcd(b, r)$.
As a base case, we can consider $gcd(a, 0) = a$.

\index{Euclid's algorithm}
\index{algorithm!Euclid}

Write a function called
\verb"gcd" that takes parameters {\tt a} and {\tt b}
and returns their greatest common divisor.  If you need
help, see \url{wikipedia.org/wiki/Euclidean_algorithm}.

\end{ex}

\begin{ex}

The Hofstadter Female and Male sequences are two sequences of integers
defined in terms of each other, such that:

\begin{align*}
F(0) &= 1; M(0) = 0 \\
F(n) &= n - M(F(n-1)), n>0 \\
M(n) &= n - F(M(n-1)), n>0
\end{align*}

The first few terms of the sequences are:

\begin{align*}
F:& 1, 1, 2, 2, 3, 3, 4, 5, 5,... \\
M:& 0, 0, 1, 2, 2, 3, 4, 4, 5,... 
\end{align*}

Write two mutually recursive functions to find the n-th term of the 
sequences.

\end{ex}

\chapter{Algorithms}
%serious edit here!!

An algorithm is a general method of solving some class of problems. You use many algoirthms every day: knowing how to add two numbers, for example, requires some simple algorithm, as does any other mathematical operation. Almost every non-trivial program you will ever write will involve some sort of algorithm, so algorithm-finding is one of the fullest and most interesting branches of computer science.

\section{Square roots}

\index{square root}

Recursion or looping is often used in programs that compute
numerical results by starting with an approximate answer and
iteratively improving it.

\index{Newton's method}

For example, one way of computing square roots is Newton's method.
Suppose that you want to know the square root of $a$.  If you start
with almost any estimate, $x$, you can compute a better
estimate with the following formula:

\[ y = \frac{x + a/x}{2} \]
%
For example, if $a$ is 4 and $x$ is 3:

\beforeverb
\begin{verbatim}
# let a = 4.0;;
# let x = 3.0;;
# let y = (x +. a/.x) /. 2.0;;
val y : float = 2.16666666666666652
\end{verbatim}
\afterverb
%
Which is closer to the correct answer ($\sqrt{4} = 2$).  If we
repeat the process with the new estimate, it gets even closer:

\beforeverb
\begin{verbatim}
# let x = y;;
# let y = (x +. a/.x) /. 2.0;;
val y : float = 2.00641025641025639
\end{verbatim}
\afterverb
%
After a few more updates, the estimate is almost exact:

\beforeverb
\begin{verbatim}
# let x = y;;
# let y = (x +. a/.x) /. 2;;
val y : float = 2.00001024002621453
# let x = y;;
# let y = (x +. a/.x) /. 2;;
val y : float = 2.00000000002621459
\end{verbatim}
\afterverb
%
In general we don't know ahead of time how many steps it takes
to get to the right answer, but we know when we get there
because the estimate
stops changing:

\beforeverb
\begin{verbatim}
# let x = 2.0;;
# let y = (x +. a/.x) /. 2;;
val y : float = 2.
# let x = y;;
# let y = (x +. a/.x) /. 2;;
val y : float = 2.
\end{verbatim}
\afterverb
%
When {\tt y == x}, we can stop.  Here is a function that starts
with an initial estimate, {\tt x}, and improves it until it
stops changing:

\beforeverb
\begin{verbatim}
let rec sqroot a x y = 
	if x=y
	then y
	else let ynew = (x +. a/.x) /. 2.0
		in sqroot a y ynew;;
\end{verbatim}
\afterverb
%
For most values of {\tt a} this works fine, but in general it is
dangerous to test {\tt float} equality.
Floating-point values are only approximately right:
most rational numbers, like $1/3$, and irrational numbers, like
$\sqrt{2}$, can't be represented exactly with a {\tt float}.

\index{floating-point}
\index{epsilon}

Rather than checking whether {\tt x} and {\tt y} are exactly equal, it
is safer to use the built-in function {\tt abs} to compute the
absolute value, or magnitude, of the difference between them:

\beforeverb
\begin{verbatim}
    if abs (y-x) < epsilon
\end{verbatim}
\afterverb
where \verb"epsilon" has a value like {\tt 0.0000001} that
determines how close is close enough.

\begin{ex}
\label{square_root}
\index{encapsulation}

Encapsulate this recursive function called \verb"square_root"
that takes {\tt a} as a parameter, chooses a reasonable
value of {\tt epsilon}, and returns an estimate of the square root
of {\tt a}.
\end{ex}

\section{Algorithms}
\index{algorithm}

Newton's method is an example of an {\bf algorithm}: it is a
mechanical process for solving a category of problems (in this
case, computing square roots).

It is not easy to define an algorithm.  It might help to start
with something that is not an algorithm.  When you learned
to multiply single-digit numbers, you probably memorized the
multiplication table.  In effect, you memorized 100 specific solutions.
That kind of knowledge is not algorithmic.

But if you were ``lazy,'' you probably cheated by learning a few
tricks.  For example, to find the product of $n$ and 9, you can
write $n-1$ as the first digit and $10-n$ as the second
digit.  This trick is a general solution for multiplying any
single-digit number by 9.  That's an algorithm!

\index{addition with carrying}
\index{carrying, addition with}
\index{subtraction!with borrowing}
\index{borrowing, subtraction with}

Similarly, the techniques you learned for addition with carrying,
subtraction with borrowing, and long division are all algorithms.  One
of the characteristics of algorithms is that they do not require any
intelligence to carry out.  They are mechanical processes in which
each step follows from the last according to a simple set of rules.

In my opinion, it is embarrassing that humans spend so much time in
school learning to execute algorithms that, quite literally, require
no intelligence.

On the other hand, the process of designing algorithms is interesting,
intellectually challenging, and a central part of what we call
programming.

Some of the things that people do naturally, without difficulty or
conscious thought, are the hardest to express algorithmically.
Understanding natural language is a good example.  We all do it, but
so far no one has been able to explain {\em how} we do it, at least
not in the form of an algorithm.


\section{Debugging}

As you start writing bigger programs, you might find yourself
spending more time debugging.  More code means more chances to
make an error and more place for bugs to hide.

\index{debugging!by bisection}
\index{bisection, debugging by}

One way to cut your debugging time is ``debugging by bisection.''
For example, if there are 100 lines in your program and you
check them one at a time, it would take 100 steps.

Instead, try to break the problem in half.  Look at the middle
of the program, or near it, for an intermediate value you
can check.  Add a {\tt print} statement (or something else
that has a verifiable effect) and run the program.

If the mid-point check is incorrect, there must be a problem in the
first half of the program.  If it is correct, the problem is
in the second half.

Every time you perform a check like this, you halve the number of
lines you have to search.  After six steps (which is fewer than 100),
you would be down to one or two lines of code, at least in theory.

In practice it is not always clear what
the ``middle of the program'' is and not always possible to
check it.  It doesn't make sense to count lines and find the
exact midpoint.  Instead, think about places
in the program where there might be errors and places where it
is easy to put a check.  Then choose a spot where you
think the chances are about the same that the bug is before
or after the check.

\section{Glossary}

\begin{description}
%write things here!
\item stuff

\end{description}


\section{Exercises}

\begin{ex}

\index{algorithm!square root}

To test the square root algorithm in this chapter, you could compare
it with {\tt sqrt}.  Write a function named \verb"test_square_root"
that prints a table something like this:

\beforeverb
\begin{verbatim}
1.0 1.0           1.0           0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0           2.0           0.0
5.0 2.2360679775  2.2360679775  0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0           3.0           0.0

\end{verbatim}
\afterverb
%
The first column is a number, $a$; the second column is
the square root of $a$ computed with the function from
Exercise~\ref{square_root}; the third column is the square root computed
by {\tt sqrt}; the fourth column is the absolute value
of the difference between the two estimates.
\end{ex}

\begin{ex}

\index{Ramanujan, Srinivasa}

The brilliant mathematician Srinivasa Ramanujan found an
infinite series\footnote{See \url{wikipedia.org/wiki/Pi}.}
that can be used to generate a numerical
approximation of $\pi$:

\index{pi}

\[\frac{1}{\pi} = \frac{2\sqrt{2}}{9801} 
\sum^\infty_{k=0} \frac{(4k)!(1103+26390k)}{(k!)^4 396^{4k}} \]

Write a function called \verb"estimate_pi" that uses this formula
to compute and return an estimate of $\pi$.  It should use recursion 
to compute terms of the summation until the last term is
smaller than {\tt 10.**(-15)}.
\end{ex}


\chapter{Strings}
\label{strings}


\section{A string is a sequence}
\index{sequence}
\index{character}
\index{bracket operator}
\index{operator!bracket}

A string is a {\bf sequence} of characters.  
You can access the characters one at a time with the
bracket operator:

\beforeverb
\begin{verbatim}
# let fruit = "banana";;
# let letter = fruit.[1]
\end{verbatim}
\afterverb
%
The second statement selects character number 1 from {\tt
fruit} and assigns it to {\tt letter}. Note that the type 
of {\tt letter} is {\tt char} not {\tt string}.

\index{index}

The expression in brackets is called an {\bf index}.  
The index indicates which character in the sequence you
want (hence the name).

But you might not get what you expect:

\beforeverb
\begin{verbatim}
# letter
- : char = 'a'
\end{verbatim}
\afterverb
%
For most people, the first letter of \verb"'banana'" is {\tt b}, not
{\tt a}.  But for computer scientists, the index is an offset from the
beginning of the string, and the offset of the first letter is zero.

\beforeverb
\begin{verbatim}
let letter = fruit.[0]
val letter : char = 'b'
\end{verbatim}
\afterverb
%
So {\tt b} is the 0th letter (``zero-eth'') of \verb"'banana'", {\tt a}
is the 1th letter (``one-eth''), and {\tt n} is the 2th (``two-eth'')
letter.

\index{index!starting at zero}
\index{zero, index starting at}

You can use any expression, including variables and operators, as an
index, but the value of the index has to be an integer.  Otherwise you
get:

\index{index}
\index{exception!TypeError}
\index{TypeError}

\beforeverb
\begin{verbatim}
# let letter = fruit[1.5]
Error: This expression has type float but an expression was expected of type
	 int.
\end{verbatim}
\afterverb
%

Note that {\tt fruit.[i]} is the same as typing {\tt String.get fruit i}.

Strings are mutable; you can change the value of characters within the 
string using the {\tt set} function:

\beforeverb
\begin{verbatim}
# fruit.[1]<-'b';;
- : unit = ()
# fruit;;
- : string = "bbnana"
\end{verbatim}
\afterverb

Note that this is equivalent to writing {\tt String.set fruit 1 'b'}. If you 
try to set a character outside of a string, then you'll get an exception error.

\section{{\tt String.length}}

\index{String module}
\index{String.length function}
\index{function!String.length}

Many useful string operations can be found in the {\tt String} module.
{\tt String.length} is a built-in function that returns the number of 
characters in a string:

\beforeverb
\begin{verbatim}
>>> fruit = 'banana'
>>> len(fruit)
6
\end{verbatim}
\afterverb
%
To get the last letter of a string, you might be tempted to try something
like this:

\index{exception!IndexError}
\index{IndexError}

\beforeverb
\begin{verbatim}
# let len = String.legnth fruit;;
# let last = fruit.[length];;
Exception: Invalid_argument "index out of bounds"
\end{verbatim}
\afterverb
%
The reason for the {\tt Exception} is that there is no letter in {\tt
'banana'} with the index 6.  Since we started counting at zero, the
six letters are numbered 0 to 5.  To get the last character, you have
to subtract 1 from {\tt length}:

\beforeverb
\begin{verbatim}
# let last = fruit[len-1]
val last: char = 'a'
\end{verbatim}
\afterverb
%

\section{Substrings}

One thing you'll want to be able to do with strings is select {\bf substrings},
or sections of strings that are themselves strings. We saw an example of this 
before in the palindromes exercise:

\beforeverb
\begin{verbatim}
let middle word = 
	let len = String.length word - 2 in
	String.sub word 1 len
\end{verbatim}
\afterverb
In this example, we're extracting the substring of all the characters between 
the first and last character.


\section{String Traversal}
\label{for}

\index{traversal}
\index{recursion!traversal}

A lot of computations involve processing a string one character at a
time.  Often they start at the beginning, select each character in
turn, do something to it, and continue until the end.  This pattern of
processing is called a {\bf traversal}.  One way to write a traversal
is with recursion and substrings:

\beforeverb
\begin{verbatim}
let rec traverse_print s = 
	print_char s.[0]; print_newline();
	let len = String.length s in
		if len=1
		then ()
		else traverse_print (String.sub s 1 (len - 1));;\end{verbatim}
\afterverb
%
This function traverses the string and displays each letter on a line by
itself. It does this by using a recursive loop that prints the first letter
than recursively calls itself on the substring that is the string without
the first letter.

\begin{ex}
Write a function that takes a string as an argument
and displays the letters backward, one per line.
\end{ex}

\index{concatenation}
\index{abecedarian}
\index{McCloskey, Robert}

The following example shows how to use concatenation (string addition)
and a {\tt for} loop to generate an abecedarian series (that is, in
alphabetical order).  In Robert McCloskey's book {\em Make
Way for Ducklings}, the names of the ducklings are Jack, Kack, Lack,
Mack, Nack, Ouack, Pack, and Quack.  This loop outputs these names in
order:

\beforeverb
\begin{verbatim}
let prefixes = "JKLMNOPQ";;
let suffix = "ack";;

let rec ducklings prefixes suffix = 
	let prefix = String.sub prefixes 0 1 in
	print_string (prefix^suffix); print_newline();
	let len = String.length prefixes in
		if len == 1
		then ()
		else ducklings (String.sub prefixes 1 (len-1)) suffix;;
\end{verbatim}
\afterverb
%
The output is:

\beforeverb
\begin{verbatim}
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
- : unit = ()
\end{verbatim}
\afterverb
%
Of course, that's not quite right because ``Ouack'' and
``Quack'' are misspelled.

\begin{ex}
Modify the program to fix this error.
\end{ex}

\section{Searching}
\label{find}

What does the following code do?

\index{find function}
\index{function!find}

\beforeverb
\begin{verbatim}
let rec find_helper ctr word letter = 
	if word.[0]=letter
	then ctr
	else let len = String.length word in
		if len = 1
		then -1
		else
		let ctr = ctr+1 in
		let word = String.sub word 1 (len-1) in
		find_helper ctr word letter;;

let find = find_helper 0;;
\end{verbatim}
\afterverb
%
In a sense, {\tt find} is the opposite of the {\tt .[]} operator.
Instead of taking an index and extracting the corresponding character,
it takes a character and finds the index where that character
appears.  If the character is not found, the function returns {\tt
-1}.

If the character doesn't appear in the string, the function returns 
{\tt -1}.

This pattern of computation---traversing a sequence and returning
when we find what we are looking for---is a called a {\bf search}.

\index{traversal}
\index{search pattern}
\index{pattern!search}

\begin{ex}
Modify {\tt find} so that it finds the last
instance of the letter, rather than the first.
\end{ex}

\begin{ex}
Modify {\tt find} so that it has a
third parameter, the index in {\tt word} where it should start
looking.
\end{ex}

\begin{ex}
Write a function {\tt count} that takes a string input and a 
character input and counts the number of times that character
appears and returns that value.
\end{ex}

\section{String comparison}

\index{string!comparison}
\index{comparison!string}

The relational operators work on strings.  To see if two strings are equal:

\beforeverb
\begin{verbatim}
if word = "banana":
    then print_string  "All right, bananas. \n";;
\end{verbatim}
\afterverb
%
Other relational operations are useful for putting words in alphabetical
order:

\beforeverb
\begin{verbatim}
let is_bananas word = print_string
	(match word with 
	"bananas" -> "Your string is bananas! \n"
	| w when w<"bananas" -> word^" is less than bananas. \n"
	| _ -> word^" is more than bananas. \n");;
\end{verbatim}
\afterverb

OCaml does not handle uppercase and lowercase letters the same way
that people do.  All the uppercase letters come before all the
lowercase letters, so:

\beforeverb
\begin{verbatim}
# is_bananas "pineapple";;
pineapple is more than bananas.
- : unit = ()
# is_bananas "Pineapple";;
Pineapple is less than bananas.
- : unit = ()
\end{verbatim}
\afterverb
%
A common way to address this problem is to convert strings to a
standard format, such as all lowercase, before performing the
comparison.  Keep that in mind in case you have to defend yourself
against a man armed with a Pineapple.

\section{Debugging}
\index{debugging}

\index{traversal}

When you use indices to traverse the values in a sequence,
it is tricky to get the beginning and end of the traversal
right. For debugging this kind of error, first try printing
the values of the indices immediately before the line where 
the error appears. Now when you run the program again, you'll 
get more information:

%edit here - provide example (Allen's was to check if two strings are the reverse of each other.)

\section{Glossary}

\begin{description}
%edit here
\item[sequence:] An ordered set; that is, a set of
values where each value is identified by an integer index.
\index{sequence}

\item[item:] One of the values in a sequence.
\index{item}

\item[index:] An integer value used to select an item in
a sequence, such as a character in a string.
\index{index}

\item[slice:] A part of a string specified by a range of indices.
\index{slice}

\item[empty string:] A string with no characters and length 0, represented
by two quotation marks.
\index{empty string}

\item[immutable:] The property of a sequence whose items cannot
be assigned.
\index{immutability}

\item[traverse:] To iterate through the items in a sequence,
performing a similar operation on each.
\index{traversal}

\item[search:] A pattern of traversal that stops
when it finds what it is looking for.
\index{search pattern}
\index{pattern!search}

\item[counter:] A variable used to count something, usually initialized
to zero and then incremented.
\index{counter}

\item[method:] A function that is associated with an object and called
using dot notation.
\index{method}

\item[invocation:] A statement that calls a method.
\index{invocation}

\end{description}


\section{Exercises}

\begin{ex}
\index{string method}
\index{method!string}

Read the documentation of the String module at
\url{http://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html}.
You might want to experiment with some of them to make sure
you understand how they work.  {\tt index} and
{\tt iter} are particularly useful.

\end{ex}

% \begin{ex}
% The following functions are all {\em intended} to check whether a
% string contains any lowercase letters, but at least some of them are
% wrong.  For each function, describe what the function actually does
% (assuming that the parameter is a string).
% %edit here
% \beforeverb
% \begin{verbatim}
% def any_lowercase1(s):
%     for c in s:
%         if c.islower():
%             return True
%         else:
%             return False
% 
% def any_lowercase2(s):
%     for c in s:
%         if 'c'.islower():
%             return 'True'
%         else:
%             return 'False'
% 
% def any_lowercase3(s):
%     for c in s:
%         flag = c.islower()
%     return flag
% 
% def any_lowercase4(s):
%     flag = False
%     for c in s:
%         flag = flag or c.islower()
%     return flag
% 
% def any_lowercase5(s):
%     for c in s:
%         if not c.islower():
%             return False
%     return True
% \end{verbatim}
% \afterverb
% 
% \end{ex}
% 

\begin{ex}
\index{letter rotation}
\index{rotation, letter}

\label{exrotate}
ROT13 is a weak form of encryption that involves ``rotating'' each
letter in a word by 13 places\footnote{See
  \url{wikipedia.org/wiki/ROT13}.}.  To rotate a letter means
to shift it through the alphabet, wrapping around to the beginning if
necessary, so 'A' shifted by 3 is 'D' and 'Z' shifted by 1 is 'A'.

Write a function called \verb"rotate_word"
that takes a string and an integer as parameters, and that returns
a new string that contains the letters from the original string
``rotated'' by the given amount.  

For example, ``cheer'' rotated by 7 is ``jolly'' and ``melon'' rotated
by -10 is ``cubed''.  

%For example ``sleep''
%rotated by 9 is ``bunny'' and ``latex'' rotated by 7 is ``shale''.

You might want to use the built-in {\tt String.iter} function, and
you'll probably find at least a couple of the functions at
\url{http://gallium.inria.fr/~remy/poly/ocaml/htmlman/libref/Char.html}
useful.

Potentially offensive jokes on the Internet are sometimes encoded
in ROT13.  If you are rather bored by not easily offended, find and 
decode some of them.
\end{ex}


% \chapter{Case study: word play}
% 
% \section{Reading word lists}
% \label{wordlist}
% 
% For the exercises in this chapter we need a list of English words.
% There are lots of word lists available on the Web, but the one most
% suitable for our purpose is one of the word lists collected and
% contributed to the public domain by Grady Ward as part of the Moby
% lexicon project\footnote{\url{wikipedia.org/wiki/Moby_Project}.}.  It
% is a list of 113,809 official crosswords; that is, words that are
% considered valid in crossword puzzles and other word games.  In the
% Moby collection, the filename is {\tt 113809of.fic}; I include a copy
% of this file, with the simpler name {\tt words.txt}, along with
% Swampy.
% 
% \index{Swampy}
% \index{crosswords}
% 
% This file is in plain text, so you can open it with a text
% editor, but you can also read it from Python.  The built-in
% function {\tt open} takes the name of the file as a parameter
% and returns a {\bf file object} you can use to read the file.
% 
% \index{open function}
% \index{function!open}
% \index{plain text}
% \index{text!plain}
% \index{object!file}
% \index{file object}
% 
% \beforeverb
% \begin{verbatim}
% >>> fin = open('words.txt')
% >>> print fin
% <open file 'words.txt', mode 'r' at 0xb7f4b380>
% \end{verbatim}
% \afterverb
% %
% {\tt fin} is a common name for a file object used for
% input.  Mode \verb"'r'" indicates that this file is open for
% reading (as opposed to \verb"'w'" for writing).
% 
% \index{readline method}
% \index{method!readline}
% 
% The file object provides several methods for reading, including
% {\tt readline}, which reads characters from the file
% until it gets to a newline and returns the result as a
% string:
% 
% \beforeverb
% \begin{verbatim}
% >>> fin.readline()
% 'aa\r\n'
% \end{verbatim}
% \afterverb
% %
% The first word in this particular list is ``aa,'' which is a kind of
% lava.  The sequence \verb"\r\n" represents two whitespace characters,
% a carriage return and a newline, that separate this word from the
% next.
% 
% The file object keeps track of where it is in the file, so
% if you call {\tt readline} again, you get the next word:
% 
% \beforeverb
% \begin{verbatim}
% >>> fin.readline()
% 'aah\r\n'
% \end{verbatim}
% \afterverb
% %
% The next word is ``aah,'' which is a perfectly legitimate
% word, so stop looking at me like that.
% Or, if it's the whitespace that's bothering you,
% we can get rid of it with the string method {\tt strip}:
% 
% \index{strip method}
% \index{method!strip}
% 
% \beforeverb
% \begin{verbatim}
% >>> line = fin.readline()
% >>> word = line.strip()
% >>> print word
% aahed
% \end{verbatim}
% \afterverb
% %
% You can also use a file object as part of a {\tt for} loop.
% This program reads {\tt words.txt} and prints each word, one
% per line:
% 
% \index{open function}
% \index{function!open}
% 
% \beforeverb
% \begin{verbatim}
% fin = open('words.txt')
% for line in fin:
%     word = line.strip()
%     print word
% \end{verbatim}
% \afterverb
% %
% 
% \begin{ex}
% Write a program that reads {\tt words.txt} and prints only the
% words with more than 20 characters (not counting whitespace).
% 
% \index{whitespace}
% 
% \end{ex}
% 
% \section{Exercises}
% 
% There are solutions to these exercises in the next section.
% You should at least attempt each one before you read the solutions.
% 
% \begin{ex}
% In 1939 Ernest Vincent Wright published a 50,000 word novel called
% {\em Gadsby} that does not contain the letter ``e.''  Since ``e'' is
% the most common letter in English, that's not easy to do.
% 
% In fact, it is difficult to construct a solitary thought without using
% that most common symbol.  It is slow going at first, but with caution
% and hours of training you can gradually gain facility.
% 
% All right, I'll stop now.
% 
% Write a function called \verb"has_no_e" that returns {\tt True} if
% the given word doesn't have the letter ``e'' in it.
% 
% Modify your program from the previous section to print only the words
% that have no ``e'' and compute the percentage of the words in the list
% have no ``e.''
% 
% \index{lipogram}
% 
% \end{ex}
% 
% 
% \begin{ex} 
% Write a function named {\tt avoids}
% that takes a word and a string of forbidden letters, and
% that returns {\tt True} if the word doesn't use any of the forbidden
% letters.
% 
% Modify your program to prompt the user to enter a string
% of forbidden letters and then print the number of words that
% don't contain any of them.
% Can you find a combination of 5 forbidden letters that
% excludes the smallest number of words?
% \end{ex}
% 
% \begin{ex}
% Write a function named \verb"uses_only" that takes a word and a
% string of letters, and that returns {\tt True} if the word contains
% only letters in the list.  Can you make a sentence using only the
% letters {\tt acefhlo}?  Other than ``Hoe alfalfa?''
% \end{ex}
% 
% \begin{ex} 
% Write a function named \verb"uses_all" that takes a word and a
% string of required letters, and that returns {\tt True} if the word
% uses all the required letters at least once.  How many words are there
% that use all the vowels {\tt aeiou}?  How about {\tt aeiouy}?
% \end{ex}
% 
% \begin{ex}
% Write a function called \verb"is_abecedarian" that returns
% {\tt True} if the letters in a word appear in alphabetical order
% (double letters are ok).  
% How many abecedarian words are there?
% \end{ex}
% 
% \index{abecedarian}
% 
% 
% %\begin{ex}
% %\label{palindrome}
% %A palindrome is a word that reads the same
% %forward and backward, like ``rotator'' and ``noon.''
% %Write a boolean function named \verb"is_palindrome" that
% %takes a string as a parameter and returns {\tt True} if it is
% %a palindrome.
% 
% %Modify your program from the previous section to print all
% %of the palindromes in the word list and then print the total
% %number of palindromes.
% %\end{ex}
% 
% 
% 
% \section{Search}
% 
% \index{search pattern}
% \index{pattern!search}
% 
% All of the exercises in the previous section have something
% in common; they can be solved with the search pattern we saw
% in Section~\ref{find}.  The simplest example is:
% 
% \beforeverb
% \begin{verbatim}
% def has_no_e(word):
%     for letter in word:
%         if letter == 'e':
%             return False
%     return True
% \end{verbatim}
% \afterverb
% %
% The {\tt for} loop traverses the characters in {\tt word}.  If we find
% the letter ``e'', we can immediately return {\tt False}; otherwise we
% have to go to the next letter.  If we exit the loop normally, that
% means we didn't find an ``e'', so we return {\tt True}.
% 
% \index{traversal}
% 
% % Removing this because we haven't seen the in operator yet.
% %\index{in operator}
% %\index{operator!in}
% 
% %You could write this function more concisely using the {\tt in}
% %operator, but I started with this version because it 
% %demonstrates the logic of the search pattern.
% 
% \index{generalization}
% 
% {\tt avoids} is a more general version of \verb"has_no_e" but it
% has the same structure:
% 
% \beforeverb
% \begin{verbatim}
% def avoids(word, forbidden):
%     for letter in word:
%         if letter in forbidden:
%             return False
%     return True
% \end{verbatim}
% \afterverb
% %
% We can return {\tt False} as soon as we find a forbidden letter;
% if we get to the end of the loop, we return {\tt True}.
% 
% \verb"uses_only" is similar except that the sense of the condition
% is reversed:
% 
% \beforeverb
% \begin{verbatim}
% def uses_only(word, available):
%     for letter in word: 
%         if letter not in available:
%             return False
%     return True
% \end{verbatim}
% \afterverb
% %
% Instead of a list of forbidden letters, we have a list of available
% letters.  If we find a letter in {\tt word} that is not in
% {\tt available}, we can return {\tt False}.
% 
% \verb"uses_all" is similar except that we reverse the role
% of the word and the string of letters:
% 
% \beforeverb
% \begin{verbatim}
% def uses_all(word, required):
%     for letter in required: 
%         if letter not in word:
%             return False
%     return True
% \end{verbatim}
% \afterverb
% %
% Instead of traversing the letters in {\tt word}, the loop
% traverses the required letters.  If any of the required letters
% do not appear in the word, we can return {\tt False}.
% 
% \index{traversal}
% 
% If you were really thinking like a computer scientist, you would
% have recognized that \verb"uses_all" was an instance of a
% previously-solved problem, and you would have written:
% 
% \beforeverb
% \begin{verbatim}
% def uses_all(word, required):
%     return uses_only(required, word)
% \end{verbatim}
% \afterverb
% %
% This is an example of a program development method called {\bf problem
% recognition}, which means that you recognize the problem you are
% working on as an instance of a previously-solved problem, and apply a
% previously-developed solution.
% 
% \index{problem recognition}
% \index{development plan!problem recognition}
% 
% 
% \section{Looping with indices}
% 
% \index{looping!with indices}
% \index{index!looping with}
% 
% I wrote the functions in the previous section with {\tt for}
% loops because I only needed the characters in the strings; I didn't
% have to do anything with the indices.
% 
% For \verb"is_abecedarian" we have to compare adjacent letters,
% which is a little tricky with a {\tt for} loop:
% 
% \beforeverb
% \begin{verbatim}
% def is_abecedarian(word):
%     previous = word[0]
%     for c in word:
%         if c < previous:
%             return False
%         previous = c
%     return True
% \end{verbatim}
% \afterverb
% 
% 
% An alternative is to
% use recursion:
% 
% \beforeverb
% \begin{verbatim}
% def is_abecedarian(word):
%     if len(word) <= 1:
%         return True
%     if word[0] > word[1]:
%         return False
%     return is_abecedarian(word[1:])
% \end{verbatim}
% \afterverb
% 
% Another option is to use a {\tt while} loop:
% 
% \beforeverb
% \begin{verbatim}
% def is_abecedarian(word):
%     i = 0
%     while i < len(word)-1:
%         if word[i+1] < word[i]:
%             return False
%         i = i+1
%     return True
% \end{verbatim}
% \afterverb
% %
% The loop starts at {\tt i=0} and ends when {\tt i=len(word)-1}.  Each
% time through the loop, it compares the $i$th character (which you can
% think of as the current character) to the $i+1$th character (which you
% can think of as the next).
% 
% If the next character is less than (alphabetically before) the current
% one, then we have discovered a break in the abecedarian trend, and
% we return {\tt False}.
% 
% If we get to the end of the loop without finding a fault, then the
% word passes the test.  To convince yourself that the loop ends
% correctly, consider an example like \verb"'flossy'".  The
% length of the word is 6, so
% the last time the loop runs is when {\tt i} is 4, which is the
% index of the second-to-last character.  On the last iteration,
% it compares the second-to-last character to the last, which is
% what we want.
% 
% \index{palindrome}
% 
% Here is a version of \verb"is_palindrome" (see
% Exercise~\ref{palindrome}) that uses two indices; one starts at the
% beginning and goes up; the other starts at the end and goes down.
% 
% \beforeverb
% \begin{verbatim}
% def is_palindrome(word):
%     i = 0
%     j = len(word)-1
% 
%     while i<j:
%         if word[i] != word[j]:
%             return False
%         i = i+1
%         j = j-1
% 
%     return True
% \end{verbatim}
% \afterverb
% 
% Or, if you noticed that this is an instance of a previously-solved
% problem, you might have written:
% 
% \beforeverb
% \begin{verbatim}
% def is_palindrome(word):
%     return is_reverse(word, word)
% \end{verbatim}
% \afterverb
% 
% \index{problem recognition}
% \index{development plan!problem recognition}
% 
% Assuming you did Exercise~\ref{is_reverse}.
% 
% 
% \section{Debugging}
% 
% \index{debugging}
% \index{testing!is hard}
% \index{program testing}
% 
% Testing programs is hard.  The functions in this chapter are
% relatively easy to test because you can check the results by hand.
% Even so, it is somewhere between difficult and impossible to choose a
% set of words that test for all possible errors.
% 
% Taking \verb"has_no_e" as an example, there are two obvious
% cases to check: words that have an 'e' should return {\tt False};
% words that don't should return {\tt True}.  You should have no
% trouble coming up with one of each.
% 
% Within each case, there are some less obvious subcases.  Among the
% words that have an ``e,'' you should test words with an ``e'' at the
% beginning, the end, and somewhere in the middle.  You should test long
% words, short words, and very short words, like the empty string.  The
% empty string is an example of a {\bf special case}, which is one of
% the non-obvious cases where errors often lurk.
% 
% \index{special case}
% 
% In addition to the test cases you generate, you can also test
% your program with a word list like {\tt words.txt}.  By scanning
% the output, you might be able to catch errors, but be careful:
% you might catch one kind of error (words that should not be
% included, but are) and not another (words that should be included,
% but aren't).
% 
% In general, testing can help you find bugs, but it is not easy to
% generate a good set of test cases, and even if you do, you can't
% be sure your program is correct.
% 
% \index{testing!and absence of bugs}
% 
% According to a legendary computer scientist:
% 
% \begin{quote}
% Program testing can be used to show the presence of bugs, but never to
% show their absence!
% 
% --- Edsger W. Dijkstra
% \end{quote}
% 
% \index{Dijkstra, Edsger}
% 
% 
% \section{Glossary}
% 
% \begin{description}
% 
% \item[file object:] A value that represents an open file.
% \index{file object}
% \index{object!file}
% 
% \item[problem recognition:] A way of solving a problem by
% expressing it as an instance of a previously-solved problem.
% \index{problem recognition}
% 
% \item[special case:] A test case that is atypical or non-obvious
% (and less likely to be handled correctly).
% \index{special case}
% 
% \end{description}
% 
% 
% \section{Exercises}
% 
% \begin{ex}
% 
% \index{Car Talk}
% \index{Puzzler}
% \index{double letters}
% 
% This question is based on a Puzzler that was broadcast on the radio
% program {\em Car
%   Talk}\footnote{\url{www.cartalk.com/content/puzzler/transcripts/200725}.}:
% 
% \begin{quote}
% Give me a word with three consecutive double letters. I'll give you a
% couple of words that almost qualify, but don't. For example, the word
% committee, c-o-m-m-i-t-t-e-e. It would be great except for the `i' that
% sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could
% take out those i's it would work. But there is a word that has three
% consecutive pairs of letters and to the best of my knowledge this may
% be the only word. Of course there are probably 500 more but I can only
% think of one. What is the word?
% \end{quote}
% 
% Write a program to find it.  You can see my solution at
% \url{thinkpython.com/code/cartalk.py}.
% 
% \end{ex}
% 
% 
% \begin{ex}
% Here's another {\em Car Talk}
% Puzzler\footnote{\url{www.cartalk.com/content/puzzler/transcripts/200803}.}:
% 
% \index{Car Talk}
% \index{Puzzler}
% \index{odometer}
% \index{palindrome}
% 
% \begin{quote}
% ``I was driving on the highway the other day and I happened to
% notice my odometer. Like most odometers, it shows six digits,
% in whole miles only. So, if my car had 300,000
% miles, for example, I'd see 3-0-0-0-0-0.
% 
% ``Now, what I saw that day was very interesting. I noticed that the
% last 4 digits were palindromic; that is, they read the same forward as
% backward. For example, 5-4-4-5 is a palindrome, so my odometer
% could have read 3-1-5-4-4-5.
% 
% ``One mile later, the last 5 numbers were palindromic. For example, it
% could have read 3-6-5-4-5-6.  One mile after that, the middle 4 out of
% 6 numbers were palindromic.  And you ready for this? One mile later,
% all 6 were palindromic!
% 
% ``The question is, what was on the odometer when I first looked?''
% \end{quote}
% 
% Write a Python program that tests all the six-digit numbers and prints
% any numbers that satisfy these requirements.  You can see my solution
% at \url{thinkpython.com/code/cartalk.py}.
% 
% \end{ex}
% 
% 
% \begin{ex}
% Here's another {\em Car Talk} Puzzler you can solve with a
% search\footnote{\url{www.cartalk.com/content/puzzler/transcripts/200813}}:
% 
% \index{Car Talk}
% \index{Puzzler}
% \index{palindrome}
% 
% \begin{quote}
% ``Recently I had a visit with my mom and we realized that
% the two digits that make up my age when reversed resulted in her
% age. For example, if she's 73, I'm 37. We wondered how often this has
% happened over the years but we got sidetracked with other topics and
% we never came up with an answer.
% 
% ``When I got home I figured out that the digits of our ages have been
% reversible six times so far. I also figured out that if we're lucky it
% would happen again in a few years, and if we're really lucky it would
% happen one more time after that. In other words, it would have
% happened 8 times over all. So the question is, how old am I now?''
% 
% \end{quote}
% 
% Write a Python program that searches for solutions to this Puzzler.
% Hint: you might find the string method {\tt zfill} useful.
% 
% You can see my solution at \url{thinkpython.com/code/cartalk.py}.
% 
% \end{ex}
% 

\chapter{Lists}

\index{list}
\index{type!list}


\section{A list is a sequence}

Like a string, a {\bf list} is a sequence of values.  In a string, the
values are characters; in a list, they can be any type.  The values in
a list are called {\bf elements} or sometimes {\bf items}.

\index{element}
\index{sequence}
\index{item}

There are several ways to create a new list; the simplest is to
enclose the elements in square brackets (\verb"[" and \verb"]")
and separate them by semi-colons:

\beforeverb
\begin{verbatim}
[10; 20; 30; 40]
['crunchy frog'; 'ram bladder'; 'lark vomit']
\end{verbatim}
\afterverb
%
The first example is a list of four integers, and has type {\tt int list}.  The second is a list of
three strings, and has type {\tt string list}.  The elements of a list must be the same type. Note that
these elements could be more lists:

\beforeverb
\begin{verbatim}
[[10; 20]l[30;40]]
\end{verbatim}
\afterverb
%
A list within another list is {\bf nested}.

\index{nested list}
\index{list!nested}

A list that contains no elements is
called an empty list; you can create one with empty
brackets, \verb"[]". The empty list is, unsurprisingly, polymorphic and so
has type {\tt 'a list}.

\index{empty list}
\index{list!empty}

As you might expect, you can assign list values to variables:

\beforeverb
\begin{verbatim}
# let cheeses = ["Cheddar"; "Edam"; "Gouda"; "Tomme de Savoie"];;
# let numbers = [17; 123];;
# let empty = [];;
\end{verbatim}
\afterverb

Another way to construct a list is using the {\bf cons} operator, \verb"::", which
appends an element to the beginning of a list. The following are all equivalent:

\index{cons operator}
\index{operator!cons}

\beforeverb
\begin{verbatim}
['a';'b';'c']
'a'::['b';'c']
'a'::'b'::['c']
'a'::'b'::'c'::[]
\end{verbatim}
\afterverb
However, the following are {\it not} equivalent to the above:
\beforeverb
\begin{verbatim}
['a';'b']::['c']
'a'::'b'::'c'
['a';'b';'c']::[]
\end{verbatim}
\afterverb
Test them in the interpreter and see what these do.

It's very common in functional programming to refer to the first element 
of a list as the {\bf head} and the rest of the elements as the {\bf tail}. This
concept is so common, in fact, that ocaml has a built-in function to extract them:

\beforeverb
\begin{verbatim}
# List.hd cheeses;;
- : string = "Cheddar"
#List.tl cheeses;;
- : string list = ["Edam";"Gouda";"Tomme de Savoie"]
\end{verbatim}
\afterverb

\index{list!element}
\index{access}
\index{index}

We can access any element of the list by using {\tt List.nth <list> <index>}. 
Remember that the indices start at 0:

\beforeverb
\begin{verbatim}
# List.nth cheeses 0
- : string = "Cheddar"
\end{verbatim}
\afterverb
%
Unlike strings, lists aren't mutable.

\section{List operations}
\index{list!operation}

The {\tt @} operator concatenates lists:

\index{concatenation!list}
\index{list!concatenation}

\beforeverb
\begin{verbatim}
# let a = [1; 2; 3];;
# let b = [4; 5; 6];;
# let c = a@b;;
val c : int list = [1; 2; 3; 4; 5; 6]
\end{verbatim}
\afterverb
%

If you want to make a list of lists flat (i.e., turn it into a list of 
just elements, you can use {\tt List.flatten <list>}:

\beforeverb
\begin{verbatim}
# let c = [[1; 2; 3]; [3; 4; 5]];;
# List.flatten c;;
- : int list = [1; 2; 3; 4; 5; 6]
\end{verbatim}
\afterverb

You can also reverse a list:

\beforeverb
\begin{verbatim}
# let forward = [1; 2; 3; 4; 5];;
# let backward = List.rev forward;;
val backward : int list = [5; 4; 3; 2; 1];
\end{verbatim}
\afterverb

\section{List iteration, mapping and folding}

If you want to apply a function to every element in a list, 
you can use {\tt List.iter function list}. For example, let's say I wanted 
to add print every element of a list:

\beforeverb
\begin{verbatim}
# let f elem = 
    print_int elem; print_newline()
in
  List.iter f forward;;
1
2
3
4
5
- : unit = ()
\end{verbatim}
\afterverb

However, the function given to {\tt List.iter} must return a 
unit type. If we want to do something more productive - for 
example, adding a constant to a list, we need to use {\tt List.map}:

\beforeverb
\begin{verbatim}
# let add3 e = e+3 in List.map add3 forward;;
- : int list = [4; 5; 6; 7; 8]
\end{verbatim}
\afterverb

Now, what if we wanted to sum together the elements of a list? 
We could write a recursive function to add together the elements, 
or would could {\bf fold} the list:

\beforeverb
\begin{verbatim}
# List.fold_left (+) 0 forward;;
- : int = 15
\end{verbatim}
\afterverb

Note that this is {\tt \verb"fold_left"}, which operates from left to right. 
There's also {\tt \verb"fold_right"}, which operates the opposite direction. 
Naturally, for addition, there's no difference when you're adding, but 
in some cases the result will be different.

We haven't seen the syntax for the first argument before - putting an operator 
between parentheses turns it into a regular function.

The second argument is the initial value - if we had used an empty list, we 
would have returned this value. If we instead used 2, we would have gotten the 
result of 17.

The last argument is the list, of course. We can encapsulate this as a function:

\beforeverb
\begin{verbatim}
let summer = List.fold_left (+) 0;;
\end{verbatim}
\afterverb

Let's break down what's going down here a little bit more. Essentially what we're 
doing is inserting a plus sign between each element of the list and evaluating the 
expression. Of course, the process is actually recursive: it adds the first element 
to the result of the folding the rest of the list, so on and so forth until it reaches 
the last element, which it adds to the initial condition.

\begin{ex}
Now use {\tt \verb"fold_left"} to write a function that finds the product of 
all the elements of a list. Consider carefully - what's your initial 
condition here? How do you want to handle the empty list?
\end{ex}

\section{Traversing a list}
\index{list!traversal}
\index{traversal!list}
\index{for loop}
\index{loop!for}
\index{statement!for}
The most common way to traverse the elements of a list is, 
in case you couldn't guess by now, is with recursion.  This 
is where list-builder notation and the idea of the head and 
the tail becomes useful.

\beforeverb
\begin{verbatim}
let rec printer lst = match lst with
	[] -> print_string "All done! \n"
	| hd::tl -> print_string hd;
		print_newline();
		printer tl;;

let cheeses = ["Cheddar"; "Edam"; "Gouda"; "Tomme de Savoie"]

# printer cheeses;;
Cheddar
Edam
Gouda
Tomme de Savoie
All done!
- : unit = ()

\end{verbatim}
\afterverb
%

Though recursive list traversal is often very useful, if you
are thinking about doing it, you should first stop and think 
about whether or not you really want {\tt List.iter}, {\tt List.map},
or list folding.

\index{item update}
\index{update!item}

\section{List sorting}

\begin{ex}
Write a function that takes a list of integers as an argument 
and returns a list of the same elements in increasing numeric 
order.

Note: if you look at the OCaml List module, you'll find several
useful functions that will make this trivial. In general, it's 
always a good idea to see if somebody has already coded solutions 
relating to your problem, but for pedagogy's sake, don't do that 
right now. We'll talk about some of those built-ins later.
\end{ex}

OCaml provides a few useful built-in functions to help with list 
sorting. The most useful of these is, unsurprisingly, {\tt List.sort}.
This is an example of a higher-order function: it takes two arguments, 
a function to use to determine the sort order, and the list itself.
\footnote{Experienced programmers will be interested to know that this 
built-in function uses a merge sort and is not tail-recursive.}

The sorting function must take two arguments of the same type, whatever 
the type of the list to be sorted is (or polymorphic), and it must return
a positive integer if the first element comes after the second element, 
zero if they are equal, and a negative integer if the first element comes 
first.

Let's look at an example of sorting a list of integers in increasing order:

\beforeverb
\begin{verbatim}
let sort_help e1 e2 = if e1>e2
	then 1
	else if e1=e2
	then 0
	else -1;;

let sorter lst = List.sort sort_help lst;;

let l1 = [4; 6; 8; 3; 5; 1; 2];;

# sorter l1;;
- : int list =[1; 2; 3; 4; 5; 6; 8]
\end{verbatim}
\afterverb

You may have noticed, if you loaded the code above, that
\verb"sort_help" and sorter are both polymorphic. This makes sense, 
since {\tt >} is polymorphic. In fact, the sort we just wrote
works on any basic data type:

\beforeverb
\begin{verbatim}
let cheeses = ["Gouda"; "Cheddar"; "Tomme de Savoie"; "Edam"];;

# sorter cheeses;;
- : string list = ["Cheddar"; "Edam"; "Gouda"; "Tomme de Savoie"]
\end{verbatim}
\afterverb
Our sort function sorted the list into increasing alphabetical order!
However, as you might expect from before, lower case doesn't work quite 
right:

\beforeverb
\begin{verbatim}
let cheeses = ["Gouda"; "Cheddar"; "Tomme de Savoie"; "edam"];;

#sorter cheeses;
- : string list = ["Cheddar"; "Gouda"; "Tomee de Savoie"; "edam"]
\end{verbatim}
\afterverb
As a computer, that makes perfect sense, but as a human, it's not 
quite what we'd usually expect. If you want to sort a list alphabetically,
you'll have to do a little more work. Often it's easiest just to make 
everything lower case.

OCaml also has a built-in function {\tt compare} that works on most 
data types for sorting.

\index{Anonymous functions}
\index{Functions!Anonymous}
This is where {\bf anonymous functions} can be useful. An anonymous function
is just like any other function, but we don't assign it a name. However, 
wherever we would put a function call, we can put an anonymous function to 
achieve the same effect. For example, if we want to square a number, we could
write a function {\tt square} that would do that for us, but if we only need 
to do it once, we can just write an anonymous function:

\beforeverb
\begin{verbatim}
# (fun x -> x*x) 3;;
- : int = 9
\end{verbatim}
\afterverb

It may not be immediately apparent why this is useful, but you'll see.
In the meantime, note the syntax - {\tt fun} lets the compiler know that
this is a function. Then, the left-hand side of the arrow operator (of 
pattern-matching fame) is the arguments taken by the function, and the
right-hand side is what the function returns. We can use this to define
named functions, by the way:

\beforeverb
\begin{verbatim}
# let square = fun x -> x*x;;
val square : int -> int = <fun>
\end{verbatim}
\afterverb
This is completely equivalent to our previous function-defining syntax. It's
not normally used, but is actually kind of a good way of thinking about what's
going on when you define a function.

We can use anonymous functions to within defining {\tt sorter} to make our
code a little more concise:

\beforeverb
\begin{verbatim}
let sorter lst = List.sort (fun e1 e2 -> e1-e2) lst;; 
\end{verbatim}
\afterverb

\section{Lists and Recursion}

Recursion and lists go together like bagels and cream cheese, 
but less fattening.

One thing we might want to do is use a loop to build up a list. 
Let's say you wanted to write a function {\tt range} 
that takes two integer arguments and returns a list of all integers
in between the two arguments, inclusive. You might write a function 
that looks a bit like this:

\beforeverb
\begin{verbatim}
let rec range_helper m n accum = 
	if m=n
	then n::accum
	else (range_helper m (n-1) (n::accum));;

let range m n = 
	if m>n 
	then range_helper n m []
	else range_helper m n [];;
\end{verbatim}
\afterverb

We can also use recursion over the elements of a list 
to return a result. For instance, we could add up all 
the elements of a list:\footnote{You could, of course, 
also use list folding to do this.}

\beforeverb
\begin{verbatim}
let rec sum_help lst accum = 
	match lst with
	[] -> accum
	| h::t -> sum_help t (h+accum);;

let summer lst = 
	sum_help lst 0;;
\end{verbatim}
\afterverb

Both of these patterns are very important in functional 
programming in OCaml.

\section{Debugging}
\index{debugging}
% write here

% OCaml's choice to make lists immutable avoids a lot of 
% possible careless mistatkes. Nonetheless, Careless use 
% of lists can lead to long hours of debugging.  Here are 
% some common pitfalls and ways to avoid them:
% 
% \begin{enumerate}
% 
% 
% \end{enumerate}
% 


\section{Glossary}

\begin{description}

\item[list:] An ordered sequence of values.
\index{list}

\item[element:] One of the values in a list (or other sequence),
also called items.
\index{element}

% \item[index:] An integer value that indicates an element in a list.
% \index{index}
% 
\item[nested list:] A list that is an element of another list.
\index{nested list}

\item[list traversal:] The sequential accessing of each element in a list.
\index{list!traversal}

% \item[mapping:] A relationship in which each element of one set
% corresponds to an element of another set.  For example, a list is
% a mapping from indices to elements.
% \index{mapping}
% 
% \item[accumulator:] A variable used in a loop to add up or
% accumulate a result.
% \index{accumulator}
% 
% \item[augmented assignment:] A statement that updates the value
% of a variable using an operator like \verb"+=".
% \index{assignment!augmented}
% \index{augmented assignment}
% 
% \index{traversal}

\item[reduce:] A processing pattern that traverses a sequence 
and accumulates the elements into a single result.
\index{reduce pattern}
\index{pattern!reduce}

\item[map:] A processing pattern that traverses a sequence and
performs an operation on each element.
\index{map pattern}
\index{pattern!map}

\item[filter:] A processing pattern that traverses a list and
selects the elements that satisfy some criterion.
\index{filter pattern}
\index{pattern!filter}

% \item[object:] Something a variable can refer to.  An object
% has a type and a value.
% \index{object}
% 
% \item[equivalent:] Having the same value.
% \index{equivalent}
% 
% \item[identical:] Being the same object (which implies equivalence).
% \index{identical}
% 
% \item[reference:] The association between a variable and its value.
% \index{reference}
% 
% \item[aliasing:] A circumstance where two or more variables refer to the same
% object.
% \index{aliasing}
% 
% \item[delimiter:] A character or string used to indicate where a
% string should be split.
% \index{delimiter}
% 
\end{description}


\section{Exercises}

\begin{ex}
Write a function that takes a list of numbers and returns the
cumulative sum; that is, a new list where the $i$th element
is the sum of the first $i+1$ elements from the original list.
For example, the cumulative sum of {\tt [1, 2, 3]} is
{\tt [1, 3, 6]}. 
\end{ex}

\begin{ex}
Write a function that removes the nth element of a list.
\end{ex}

\begin{ex}
Write a function that removes the first element of a list that
matches a provided argument. Modify it to remove all matching 
elements of the list.
\end{ex}


\begin{ex}
Write a function called \verb"is_sorted" that takes a list as a
parameter and returns {\tt True} if the list is sorted in ascending
order and {\tt False} otherwise.  You can assume (as a precondition)
that the elements of the list can be compared with the relational
operators {\tt <}, {\tt >}, etc.

\index{precondition}

For example, \verb"is_sorted [1; 2; 2]" should return {\tt True}
and \verb"is_sorted ['b'; 'a']" should return {\tt False}.
\end{ex}

\begin{ex}
Write a function to turn a list of characters into a string. Write
another function to do the reverse task.
\end{ex}

\begin{ex}
\label{anagram}

\index{anagram}

Two words are anagrams if you can rearrange the letters from one
to spell the other.  Write a function called \verb"is_anagram"
that takes two strings and returns {\tt True} if they are anagrams.
\end{ex}


\begin{ex}
\label{duplicate}

The (so-called) Birthday Paradox:

\begin{enumerate}

\index{birthday paradox}
\index{duplicate}

\item Write a function called \verb"has_duplicates" that takes
a list and returns {\tt True} if there is any element that
appears more than once.  It should not modify the original
list.

\item If there are 23 students in your class, what are the chances
that two of you have the same birthday?  You can estimate this
probability by generating random samples of 23 birthdays
and checking for matches.
Hint: you can generate random birthdays with the {\tt Random} module.

\index{random module}
\index{module!random}
\index{randint function}
\index{function!randint}

\end{enumerate}

You can read about this problem at
\url{wikipedia.org/wiki/Birthday_paradox}.%, and you can see my solution
%at \url{thinkpython.com/code/birthday.py}.

\end{ex}


\begin{ex}

\index{duplicate}
\index{uniqueness}

Write a function called \verb"remove_duplicates" that takes
a list and returns a new list with only the unique elements from
the original. Hint: they don't have to be in the same order.
\end{ex}


% \begin{ex}
% \index{append method}
% \index{method append}
% \index{list!concatenation}
% \index{concatenation!list}
% 
% Write a function that reads the file {\tt words.txt} and builds
% a list with one element per word.  Write two versions of
% this function, one using the {\tt append} method and the
% other using the idiom {\tt t = t + [x]}.  Which one takes
% longer to run?  Why?
% 
% You can see my solution at \url{thinkpython.com/code/wordlist.py}.
% \end{ex}
% 

\begin{ex}
\label{wordlist1}
\label{bisection}

%edit here - move to arrays section

\index{membership!bisection search}
\index{bisection search}
\index{search, bisection}

\index{membership!binary search}
\index{binary search}
\index{search, binary}

To check whether a word is in a word list, you could use
the {\tt List.exists} function, but it would be slow because it searches
through the words in order.

Because the words are in alphabetical order, we can speed things up
with a bisection search (also known as binary search), which is
similar to what you do when you look a word up in the dictionary.  You
start in the middle and check to see whether the word you are looking
for comes before the word in the middle of the list.  If so, then you
search the first half of the list the same way.  Otherwise you search
the second half.

Either way, you cut the remaining search space in half.  If the
word list has 113,809 words, it will take about 17 steps to
find the word or conclude that it's not there.

Write a function called {\tt bisect} that takes a sorted list
and a target value and returns {\tt true} if it is in the list
and {\tt false} if it's not. Bonus points if the funciton is 
polymorphic.

In trying to do this, you may find that it's exceptionally difficult
with a list. We'll see better data structures for doing this in a 
moment.

% \index{bisect module}
% \index{module!bisect}
% 
% Or you could read the documentation of the {\tt bisect} module
% and use that!
\end{ex}

\begin{ex}
\index{reverse word pair}

Two words are a ``reverse pair'' if each is the reverse of the
other.  Write a program that finds all the reverse pairs in the
word list. 
\end{ex}

\begin{ex}
\index{interlocking words}

Two words ``interlock'' if taking alternating letters from each forms
a new word\footnote{This exercise is inspired by an example at
  \url{puzzlers.org}.}.  For example, ``shoe'' and ``cold''
interlock to form ``schooled.''

\begin{enumerate}

\item Write a program that finds all pairs of words that interlock.
  Hint: don't enumerate all pairs!

\item Can you find any words that are three-way interlocked; that is,
  every third letter forms a word, starting from the first, second or
  third?

\end{enumerate}
\end{ex}

\chapter{Case Study: Regular Expressions}
\label{chap:regex}

Regular expressions exist in a lot of programming languages, and OCaml is no exception. {\bf Regular expressions}, often abbreviated as {\bf regex} or {\bf regexp}, are a powerful way of processing text, used for anything from find and replace to punctuation stripping to removing duplicate words.

\section{File I/O}

%input_char chan_in;;
%- : char = 'H'

First, we're going to want a way of reading and writing files for this
chapter. Basic file input/output (I/O, sometimes just IO) is pretty
simple in OCaml. Let's say you have a plain-text file named {\tt
  test.txt} in your current directory, which reads, ``Hi! \verb"\"n This is a
test file!'' and you want to read it into OCaml. To do so, you need to
open what's called a {\bf channel}. Channels come in two varieties,
input, or read, and output, or write. If we want to read {\tt
  test.txt}, we want an input channel:

\beforeverb
\begin{verbatim}
let chan_in = open_in "test.txt";;
val chan_in = in_channel <abstr>
\end{verbatim}
\afterverb

We can now read in the text of that file. There are two primary read functions, one to read a character at a time, and another to read an entire line at a time. There 
\beforeverb
\begin{verbatim}
# input_char chan_in;;
- : char = 'H'
# input_char chan_in;;
- : char = 'i'
# input_char chan_in;;
- : char = '!'
# input_char chan_in;;
- : char = '\n'
# input_line chan_in;;
- : string = "This is a test file!"
# input_char chan_in;;
Exception: End_of_file.
\end{verbatim}
\afterverb

As useful as it is to read a file a character or a line at a time,
sometimes we might want to move to a specific position within a file
to be able to read it there. In particular, we might want to move back
to the beginning of a file. \verb"pos_in" returns the current position
within a file, with the start of the file being position zero, of
course. \verb"seek_in" goes to a given location.

\beforeverb
\begin{verbatim}
# pos_in chan_in;;
- : int = 25;;
# seek_in chan_in 0;;
- : unit = ()
# pos_in chan_in;;
- : int = 0
# input_line chan_in;;
- : string = "Hi!"
\end{verbatim}
\afterverb
We can determine the length of the channel using \verb"in_channel_length":
\beforeverb
\begin{verbatim}
in_channel_length chan_in;;
- : int = 25
\end{verbatim}
\afterverb

We may also want to write to a file. For that, we want to create an output file:

\beforeverb
\begin{verbatim}
# let chan_out = open_out "test2.txt";;
val out_chan : out_channel <abstr>
\end{verbatim}
\afterverb

If the file you specify does not exist, it is created, and if it does,
it is truncated.\footnote{There are ways to open files in other modes,
  like append. 

For more information, look up {\tt open\_out\_gen} in the
  Pervasives module in the OCaml documentation.}

We can write to the
channel using \verb"output_char" and \verb"output_string": \beforeverb

\begin{verbatim}
# output_char chan_out 'a';;
- : unit = ()
# output_string chan_out "bcde";;
- : unit = ()
\end{verbatim}
\afterverb

We can move position in an output channel, just like in input channels:
\beforeverb
\begin{verbatim}
# pos_out chan_out;;
- : int = 5
# seek_out chan_out;;
- : unit = ()
# output_string "fg";;
- : unit = ()
\end{verbatim}
\afterverb

As you may have already noticed, nothing has actually happened to the file yet. Nothing will, until you close the file:
\beforeverb
\begin{verbatim}
# close_out chan_out;;
- : unit = ()
\end{verbatim}
\afterverb
You can now view the file. Note that it reads ``abcfg'': when we went back in the file and wrote more, it overwrote, it didn't insert. You can also close input files with \verb"close_in".

There's also a built-in output channel: the screen. It is named {\tt stdout}, and you can write to it just like any other output channel.
\beforeverb
\begin{verbatim}
output_string stdout "Hello, world!\n"
Hello, world!
- : unit = ()
\end{verbatim}
\afterverb

\section{The {\tt Str} module}

The {\tt Str} module is a very common module in OCaml coding, and it allows for a lot of functionality that experienced programmers would expect to deal with strings.

However, {\tt Str} is not a standard module, in the way that {\tt List} and {\tt String} are. In order to use it, we must first load it:
\beforeverb
\begin{verbatim}
# #load "str.cma";;
\end{verbatim}
\afterverb

We can now use functions and types defined within the module just as we would normally expect. Note that this is different than if we had called {\tt \#use}. We still call it's functions by calling {\tt Str.function}. We can now {\tt \#use} it if we so desire.

\section{Regular Expressions}

A regular expression is, at its simplest, a sequence of symbols with particular meanings that are used to {\em match} certain strings or substrings. This will make much more sense with examples. The point however, is that we can match certain strings within a document, which we can use to find information, or check that input is of a certain form, et cetera.

Perhaps the simplest regular expression is just a string. The regular expression ``{\tt a}'' will match any string or substring of exactly the form ``a''. This might be useful if we were looking for all the uses of the word ``a'' within a document, though we must be careful because it will also match any time the letter ``a'' appears {\it within} a word. It also won't generally match ``A,'' which we probably do want to match. This is, perhaps, not a compelling example; it would not be particularly difficult to find all instances of the word ``a'' without using a regular expression, especially considering all the built-in search functionality of most any text editor these days.

Fortunately, regular expressions allow us to do much cooler things. For example, we can detect the ends of words using the special ``\b'' character. If we want to find words that end in ``ly'', for example, which might make a simple method of finding most, but not all, adverbs, we can use the regular expression ``ly\b.''

Lots of useful functionality in regular expressions comes from some of its operators. Most of the notable regular expression operators are {\tt postfix} operators, meaning they operate on the character before them. For example, the ``*'' token matches the preceding expression any number of times, including zero. For example, the regular expression ``pbb*t'' would match any of ``pbt,'' ``pbbt,'' or ``pbbbbbbt.'' But that's just rude. You can also group expressions using ``\verb"\"(... \verb"\")'', and then a postfix operator after the grouping will be applied to the entire grouping, i.e., ``\\(aa\\)*'' will match any sequence with an even number of a's.

There are also character classes, which match a single character out
of a set of characters, denoted by square brackets. If we want to
match a single digit of a number, we can use the regular expression
``[0123456789],'' or ``[0-9]'' for short. You can also negate a
character set by making the first character ``\verb"^"'', which will make
the character class match any single character {\em not}
listed. ``[\verb"^"0-9]'', for example, will match any character that is not
a numeral.

Some systems of regular expressions get more complicated than this,\footnote{Technically speaking, anything that is still technically regular can be built out of these tokens, but some systems of ``regular'' expressions include some useful functionality that is not, strictly speaking regular.} but this pretty much wraps it up for regular expressions in OCaml. The syntax of regular expressions in OCaml is summed up in Table \ref{tab:regex}. They are also summarized in the ocaml Str module documentation.

\begin{tabular}{l | l | l}
\hline
Token & Description & Example \\ \hline
\verb"\b" & Matches a word boundary. & \verb"a\b" matches the second a in ``aa'' but not the first. \\ \hline
{\tt .} & Matches any character except newline & {\tt .*} will match any line of a string \\ \hline
\verb"\^" & Matches the beginning of a line or string & \verb"\^a" will match the first a in ``aa'' but not the second. \\ \hline
{\tt \$} & Matches the end of a line or string. & {\tt a\$} will match the second a in ``aa'' but not the first. \\ \hline
{\tt *} & Postfix Operator. Repeats the preceding character, zero, one, or any number of times. & {\tt a*} matches ``'', ``a'', or ``aaaaa.''\\ \hline
{\tt +} & Postfix Operator. Repeats the preceding character one or more times. & {\tt a+} matches ``a,'' or ``aaaaa.''\\ \hline
{\tt ?} & Postfix Operator. Repeats the preceding character zero or one times. & {\tt a?} matches ``'' or ``a''.\\ \hline
\verb"\|" & Infix operator. Matches either the expression before the bar or the expression after the bar, but not both at once. This is distinct from character classes in that it can operate on larger grouped expressions.  \verb"the\|a" matches ``a'' or ``the''. \\ \hline
\verb"[...]" & Defines a character class. It matches exactly one character, of any within the class. You can define a range using ``-''. To include a ``]'', make it the first character within the class. To include a ``-'', make it the first or last character of the class. Negate the class using \verb"^". & \verb"[0-9a-zA-Z]" matches any single alphanumeric character. \\ \hline
\verb"(...)" & Groups a subexpression. & \verb"Jer(ry\|i)" matches both ``Jerry'' and ``Jeri''. \\ \hline
\verb"\1" & Matches the text matched by the first subexpression. (\verb"\2" matches the second, and so on up to \verb"\9") & \verb"(the) \\1" matches ``the the''. \\ \hline
\verb"\" & Escapes a special character, i.e., one of \verb"$^.*+?[]". & \verb"\$[0-9]*" matches any even dollar amount. \\ \hline
\label{tab:regex}
\end{tabular}

Note that when entering any of the characters with a ``\verb"\\"'' in an OCaml string, you will have to double the backslash so that it doesn't try to make it into an escape sequence (unless the escape sequence is what you want, as with tab and newline).

% write here
\begin{ex} \label{ex:regex_doubles}
Write a regular expression to match doubled words, ex., ``the the''. Spend some time to think through what should and shouldn't get matched, considering cases of capitalization or different punctuation.
\end{ex}

\section{Compiling Regular Expressions}

In order to use regular expressions in OCaml, you must first compile
them. There are two functions to compile regular expressions, {\tt
  regexp} and {\tt regexp\_case\_fold}. The difference is only that the
latter ignores the difference between capital letters and lower case
letters. Otherwise, the look exactly the same, so I'll just use {\tt
  regexp} for now:

\beforeverb
\begin{verbatim}
# let r = Str.regexp "a+";;
val r : Str.regexp = <abstr>
\end{verbatim}
\afterverb

There's also {\tt quote} and {\tt regexp\_string}, both of which take a string and return a regular expression that matches exactly that string, the difference being that {\tt quote} returns it as a string and {\tt regexp\_string} returns it as a compiled regular expression:
\beforeverb
\begin{verbatim}
# let q = Str.quote "a+";;
val q : string = "a\\+"
# let r2 = Str.regexp_string "a+";;
val r2 : Str.regexp = <abstr>
\end{verbatim}
\afterverb
Note that this will match ``a+'', not ``aaa''. There's also a {\tt regexp\_string\_case\_fold}, that is {\tt regexp\_string} but case-insensitive.

\section{Using Regular Expressions: Search}

Now that we have our compiled regular expression objects, we can use them to do work for us.

First, we can check whether or not a substring matches a regular expression:
\beforeverb
\begin{verbatim}
# let s = "aaaa";;
# Str.string_match r s 0;;
- : bool = true
\end{verbatim}
\afterverb
{\tt Str.string\_match} is a function which takes a regular expression, a string, and an int, and determines whether or not a substring starting at the position specified\footnote{Strings are indexed from 0!} matches the regular expression. Note that this doesn't test the entire string, only searches for the (longest) substring starting at that position:
\beforeverb
\begin{verbatim}
# let s2 = "baaa";;
# let s3 = "aaab";;
# Str.string_match r s2 0;;
- : bool = false
# Str.string_match r s2 1;;
- : bool = true
# Str.string_match r s3 0;;
- : bool = true
\end{verbatim}
\afterverb

We can determine the string matched by \verb"string_match" by using \verb"matched_string":
\beforeverb
\begin{verbatim}
# Str.string_match r s3 0;;
# Str.matched_string s3;;
- : string = "aaa"
\end{verbatim}
\afterverb
\verb"matched_string" takes one argument: the same string passed to \verb"string_match",\footnote{Doesn't mattter why, does it?} and returns the substring which matches the regular expression. Note that shorter substrings ``aa'' and ``a'' would also match the regular expression, but it returns ``aaa''.

There are lots of other useful string-searching functions available; look them up in the OCaml documentation online.

\begin{ex}

\end{ex}

\section{Using Regular Expressions: Replacement}

You can also use regular expressions to aid in string replacement.

{\tt global\_replace} is a function that takes three arguments, the first being a regular expression. Then, wherever the regular expression matches in the last argument, it replaces it with the template defined by the second argument. That template can be, at its most basic, a string. First, let's say you wanted to replace all the instances of the letter ``a'' with the letter ``o'':
\beforeverb
\begin{verbatim}
# let r = Str.regexp "a";;
# let s = "Ya dawg";;
# let s2 = Str.global_replace r "o" s;;
s2 = "Yo dowg";;
\end{verbatim}
\afterverb
but that's not right either. We could replace only the first letter using {\tt replace\_first}, which would give us ``Yo dawg'', which is clearly the correct answer.

We can do even more with {\tt global\_replace}. The replacement template can contain {\tt \\1}, {\tt \\2}, et cetera to match the corresponding group within the part of the string matched by the regular expression. Let's use the regular expression you wrote that matched doubled words in exercise \ref{ex:regex_doubles} to remove the doubles. Chances are you wrote something that had some group that matched the text of the first word. If not, do it again.

\beforeverb
\begin{verbatim}
# let s = "Yo yo dawg dawg. That's that and and all.";;
# let s2 = Str.global_replace r_doubles "\\1" s;;
\end{verbatim}
\afterverb
Take a look at what your regular expression caught, or maybe didn't catch. Did you get rid of ``That's that''? Depending on the situation, you may or may not want to catch that. Write a version of your regular expression for both situations (you're more likely to not want to catch it, so maybe think a little harder about that one).

Once again, there are lots of other useful functions that you should take a look at in the documentation.

\section{Using Regular Expressions: Splitting}

One of the more common tasks within computer science is splitting up a string into a list of smaller strings (usually words) that are easier to process.

As a first pass, let's first break up a string into words just using a space as a delimeter:
\beforeverb
\begin{verbatim}
# let s = "this is a list of words";;
# let r = Str.regexp " ";;
# let l = Str.split r s;;
val l : string list = ["this"; "is"; "a"; "word"; "list"]
\end{verbatim}
\afterverb
The function {\tt split} takes a regular expression and a string, and returns a the string broken up into a list using strings matched the regular expression as delimiters.

As always, the documentation has some more useful functions for you.

\begin{ex}
As an exercise, write a better function to split strings into lists of words. Be sure to consider carefully how to handle things like punctuation, double spaces, tabs, and new lines.
\end{ex}

\section{Debugging}
%write here

\section{Glossary}


\chapter{Putting the O in OCaml, Part 1: Imperative programming}

Thus far, everything we've learned has been (relatively) completely functional.
However, OCaml is a practical language, and uses object-oriented functionality 
when it's, well, practical to do so. There's a lot to object-oriented programming,
but for now let's just start with the basics.

The first thing we're going to do to make OCaml objective is learn how to make 
and manipulate dynamic variables. Technically speaking, this process is imperative 
programming. However, object-oriented and imperative programming are closely tied - 
object-oriented might be thought of as built upon imperative programming - and for 
the sake of this book, I'll use the two almost interchangeably.

\section{References}

\index{References}

In function-oriented languages like OCaml, you 
aren't really supposed to change the value of 
variables. You only use them as short-hand for 
expressions. If you really want to, though, you 
can create a {\bf reference}, which functions
a lot more like an object-oriented variable. 
This is what it looks like:

\beforeverb
\begin{verbatim}
 # let my_ref = ref 100;;
val my_ref : int ref = {contents = 100}
\end{verbatim}
\afterverb

The output looks a little weird, but that's because, 
in OCaml, references take a backseat to expressions.

Now, I said you could change the value of references, 
so let's see that.

\beforeverb
\begin{verbatim}
 # my_ref := 42;;
- : unit = ()
\end{verbatim}
\afterverb

Note that the operator for changing the value of a reference is `:=' instead of just `='. Also, note that
assignment doesn't return a value, but rather returns a unit. In order to read the value of a reference, use
the `!' operator. \footnote{In many other programming languages, `!' is used to mean ``not.'' In OCaml, it's 
better to think of it as ``get''.}

\beforeverb
\begin{verbatim}
 # !my_ref;;
- : int = 42
\end{verbatim}
\afterverb

This is all fine and well. But references aren't really any more useful than variables
unless you have a more meaningful way to modify them. The most accessible
method of modifying references is using loops.

\section{Looping}

In functional programming, we don't really like loops. We'd much rather
use recursion, and you can usually use recursion instead. However, looping
can occasionally be very useful, even in otherwise mostly-functional programs.

\index{Looping}
\index{For loop}
\index{While loop}

There are two primary forms of loops: the {\tt for} loop and the {\tt while}
loop. Technically speaking, a for loop is just a particular case of a very useful
while loop, but it's also a little easier to use and a little harder to mess up, so
we'll start with that.

\subsection{For loop}

Let's look at the problem of adding itegers from 1 to n again. 
We might go about this problem by iterating through all the integers from 1 to n and 
adding them up as we go along. Well, this is exactly what a for loop is used for.

\beforeverb
\begin{verbatim}
let n = 10;;
let addup = ref 0;;
for i = 1 to n do
     addup := !addup + i
done;;
print_int !addup;;
\end{verbatim}
\afterverb

Note that I used a reference so that I could change the value of {\tt addup} every time, 
and the use of the ! to ``get'' the value of addup in order to add to it. Also note that, 
in OCaml, whatever occurs between the ``do'' and the ``done'' must evaluate to a unit. 
That means for loops cannot return a value, which makes them not particularly useful. 
Fortunately, though, the reference assignment operator (:=) does not return a value.

This is a very object-oriented approach to solving this problem. You shouldn't like it.
\footnote{Well, okay. Object-oriented solutions are very good for some problems. In this 
particular (trivial) case, I can't really say whether functional or imperative solutions 
are better (we'll see the function-oriented solution next chapter). There are definitely 
situations where one is easier, or faster, or more robust then the other.}

\subsection{While loop}

While loops are a slightly more general form of for loops, that look at a condition and
go while (hence the name) that condition is still true. Let's look at the above problem
using a while loop:

\beforeverb
\begin{verbatim}
let n = 10;;
let addup = ref 0;;
let i = ref 1;;
while !i <= n do
     addup := !addup + !i;
     i := !i + 1
done;;
print_int !addup;;
\end{verbatim}
\afterverb

You can probably see the similarity between the two different loops.

One thing to be careful of in while loops is that the condition ceases to be true at 
some point. If the condition of a while loop is always true, then you will never stop 
looping (within the technical constraints of your machine). For example, if I hadn't
made i a reference variable:
\beforeverb
\begin{verbatim}
let n = 10;;
let addup = ref 0;;
let i = 1;;
while i <= n do
     addup := !addup + i;
     i = i + 1
done;;
print_int !addup;;
\end{verbatim}
\afterverb
then the condition is always true. This is because, in the condition of the while loop,
i is always equal to 1. The statement {\tt i = i+1} is actually an equality test which will always
return false. This program will return a compile warning about how expressions within a while loop 
returning should return the unit type, and then continue to loop forever. This is known as
an {\bf infinite loop}, and they should generally be avoided.

This is all I'm going to cover for now. There's a lot more to object-oriented 
programming than this, of course, but we'll need a couple more things before
we can really cover those topics.

\section{Examples}

%write here

\chapter{Arrays}

OCaml arrays are quite a bit like lists, but with some very significant
differences, that make them suited to different tasks. The primary difference
is that while lists are immutable, arrays are not. Arrays are also much better
for selecting a random element, rather than just the first. As you might expect,
most array functions are in the {\tt Array} module. In general terms, arrays are 
a much more object-oriented data structure.

\section{Making Arrays}

In order to create an array, you can write it out as a list with vertical bars inside the square brackets, or use the {\tt make} or {\tt init} functions:

\beforeverb
\begin{verbatim}
# let arr = [|6; 7; 3; 1; 2|];;
val arr : int array = [|6; 7; 3; 1; 2|]
# let arr = Array.init 5 (fun i -> i*i);;
val arr : int array = [|0; 1; 4; 9; 16|]
# let arr = Array.make 5 1;;
val arr : int array = [|1; 1; 1; 1; 1|]
\end{verbatim}
\afterverb
As you can probably see from the examples, each way has different uses. If you want to specify every element, you'll want to write it out, though this is generally not advantageous in most applications of arrays. If there's a pattern to your elements, you want to {\tt init} the array, which takes two arguments, the length of the array and a function that takes as an argument the index of the element (starting at 0!) and returning the element (not necessarily an integer!) that goes in that spot. If you want an array with all the same element, you'll want to {\tt make} the array - the first argument is the length of the array, and the second argument is the element to fill the array. This gets more interesting when you fill it with a variable, especially a reference.

\beforeverb
\begin{verbatim}
# let x = ref 1;;
# let xarr = Array.make 4 x;;
- : int ref array  = 
[|{contents = 1}; {contents = 1}; {contents = 1}; {contents = 1}|]
# x := 2;;
- : unit = ()
# xarr;;
- : int ref array  = 
[|{contents = 2}; {contents = 2}; {contents = 2}; {contents = 2}|]
\end{verbatim}
\afterverb

This is quite interesting. The array doesn't contain four ones, it contains
four pointers to the object x. This can be useful, but it can also be dangerous.
It is an instance of a phenomenon called {\bf aliasing}, which I will discuss more
later, but the jist is that we have many ways to refer to the same object, and we 
must be careful about changing that object from one way and affecting another unexpectedly.

You can also convert arrays to lists and vice versa using 
the \verb"Array.to_list" and
\verb"Array.of_list" functions.

\section{Array Operations}

You can call a specific element of an array using {\tt get} 
or an equivalent array syntax:

\beforeverb
\begin{verbatim}
# arr;;
- : int array = [|0; 1; 4; 9; 16|]
# Array.get arr 0;;
- : int = 0
# arr.(2);;
- : int = 4
\end{verbatim}
\afterverb
Again, indices start at 0.

Arrays are mutable. To change the value of an array 
element, you can use the {\tt set} function or the 
assignment operator:

\beforeverb
\begin{verbatim}
# arr;;
- : int array = [|0; 1; 4; 9; 16|]
# Array.set arr 3 5;;
- : unit = ()
# arr;;
- : int array = [|0; 1; 4; 5; 16|]
# arr.(3) <- 7
- : unit = ()
# arr;;
- : int array = [|0; 1; 4; 7; 16|]
\end{verbatim}
\afterverb

Even though arrays are mutable, you can't change the length 
of arrays directly. There are handy ways to append arrays 
or take subarrays as new arrays, though.

\beforeverb
\begin{verbatim}
# let arr1 = [|0; 1; 2|];;
# let arr2 = [|3; 4|];;
# let subarr1 = Array.sub arr1 0 2;;
val subarr1 : int array = [|0; 1|]
# let apparr12 = Array.append arr1 arr2;;
val apparr12 = int array [|0; 1; 2; 3; 4|]
# let conarr12 = Array.concat [arr1,arr2];;
val conarr12 = int array [|0; 1; 2; 3; 4|]
\end{verbatim}
\afterverb
{\tt sub} takes an array and two integers and returns a 
subarray of that array starting at the first integer 
argument, with the length specified in the second argument. 
{\tt append} appends two arrays end-to-start. {\tt concat} 
does the same thing as {\tt append} for a list of arrays.

\section{Array Iteration, Mapping, and Folding}

Much like in lists, the Array module defines functions {\tt 
iter}, {\tt map}, {\tt \verb"fold_left"} and {\tt \verb"fold_right"}. 
They work in exactly the same way:

\beforeverb
\begin{verbatim}
let arr = [| 1; 3; 6; 2; 5|];;

print_string "Iter results:"; print_newline();
Array.iter (fun el -> print_int el; print_newline()) arr;;

print_string "Map results:"; print_newline();
Array.map (fun el -> 2*el) arr;;

print_string "Fold results:"; print_newline();
Array.fold_left (fun el1 el2 -> el1+el2) 0 arr;;

Iter results:
1
3
6
2
5
- : unit = ()
Map results:
- : int array = [|2; 6; 12; 4; 10|]
Fold results:
- : int = 17
\end{verbatim}
\afterverb

\section{Array Sorting}

You can sort arrays much like you can sort lists, using
{\tt sort}. However, it might not work as you expect:

\beforeverb
\begin{verbatim}
# let arr = [| 1; 3; 6; 2; 5|];;
# let sortarr = Array.sort compare arr;;
val sortarr : unit = ()
\end{verbatim}
\afterverb
Well, that's not right. We've sorted it into oblivion! 
But, wait, what's {\tt arr} again?

\beforeverb
\begin{verbatim}
# arr;;
- : int array = [|1; 2; 3; 5; 6|]
\end{verbatim}
\afterverb
let max arr = 
	Array.sort compare arr;
	let n = Array.length arr - 1 in 	
	arr.(n);;
{\tt arr} is sorted! This is the first example we've seen of 
{\bf side effects}, which are very common in object-oriented 
programming, but do not exist in functional programming. {\tt 
Array.sort} doesn't return a sorted array. In fact, it doesn't
really return anything - though that's not always the case in 
a function with side effects. The important part is that the 
function causes something {\it else} to happen. In this case, 
it sorts the array.

Sometimes side effects aren't the main point. For example, let's
say we wanted the largest element of an array. We might define a 
function to do it like this: 

\beforeverb
\begin{verbatim}
let max arr = 
	Array.sort compare arr;
	let n = Array.length arr - 1 in 	
	arr.(n);;
\end{verbatim}
\afterverb

This function would have the (presumably unintended) consequence of
changing the array {\tt arr} (specifically, it would sort it).

\section{Array Traversal}

Seeing as arrays are somewhat object-oriented data types, it makes sense to 
talk about traversing them in object-oriented ways. In general, you 
can, and should, use the {\tt iter} and {\tt map} functions. But this 
is a chance to show that looping can be useful.

Let's rewrite our {\tt max} function in a way that's more object-oriented - 
using a while loop:

\beforeverb
\begin{verbatim}
let max arr = 
	let curmax = ref arr.(0) and i = ref 1 in
	while !i < Array.length arr do
		if (arr.(!i) > (!curmax)) then curmax := arr.(!i);
		i := !i + 1
	done;
	!curmax;;
\end{verbatim}
\afterverb

This function traverses the loop, looking at each element, processing it,
then moves on to the next element. Note that this isn't as pretty as it 
could be - there are lots of exclamation points and the like. This is because 
OCaml is, first and foremost, a functional language, with object-oriented 
capabilities taking a back seat. Nonetheless, these kinds of patterns can be 
very useful.

\section{Glossary}

\chapter{Hashtables}
\index{hashtable}

\index{type!hashtable}
\index{key}
\index{key-value pair}
\index{index}

A {\bf hashtable} is like an array, but more general.  In a list,
the indices have to be integers; in a hashtable they can
be (almost) any type. Hashtable functions are in the {\tt Hashtbl} 
module - a great example of how computer scientists are lazy and don't 
want to write out more letters than absolutely necessary.

You can think of a hashtable as a mapping between a set of indices
(which are called {\bf keys}) and a set of values.  Each key maps to a
value.  The association of a key and a value is called a {\bf
  key-value pair} or sometimes an {\bf item}.

As an example, we'll build a hashtable that maps from English
to French words, so the keys and the values are all strings.

The function {\tt Hashtbl.create} creates a new hashtable with no items.
It takes one argument, an integer, that is the initial size of the table.
The hashtable will grow as necessary, but we have to start with something.
Adding elements above this initial guess is slower than merely
changing the preallocated ``empty'' elements. However, it is always better
to guess low and add more than preallocate too much. Think of this argument 
as a lower bound for your hashtable size.

\beforeverb
\begin{verbatim}
# let eng2fr = Hashtbl.create 10;;
val eng2fr ('_a','_b') Hashtbl.t = <abstr>
\end{verbatim}
\afterverb

Note that the type of the hashtable is {\tt Hashtbl.t}. To add an element, use the 
{\tt add} function:

\beforeverb
\begin{verbatim}
# Hashtbl.add eng2fr "hello" "bonjour";;
- : unit = ()
\end{verbatim}
\afterverb

Note that hashtables are mutable - we didn't create a new table and assign it to 
a variable, we changed the old value, and the function returned a unit.

To view an element, we use the {\tt find} function.

\beforeverb
\begin{verbatim}
# Hashtbl.find "hello";;
- : string = "bonjour"
\end{verbatim}
\afterverb

We can also replace or remove elements:

\beforeverb
\begin{verbatim}
# Hashtbl.replace eng2fr "hello" "salut";;
- : unit = ()
# Hashtbl.find eng2fr "hello";;
- : string = "salut"
# Hashtbl.remove eng2fr "hello";;
- : unit = ()
# Hashtbl.find eng2fr "hello";;
Exception: not_found
\end{verbatim}
\afterverb

You don't need to make keys unique. For example, we can have
multiple translations for ``hello'':

\beforeverb
\begin{verbatim}
# Hashtbl.add eng2fr "hello" "bonjour";;
# Hashtbl.find eng2fr "hello";;
 - : string = "bonjour"
# Hashtbl.add eng2fr "hello" "salut";;
# Hashtbl.find eng2fr "hello";;
 - : string = "salut"
# Hashtbl.find_all eng2fr "hello";;
 - : string list = ["bonjour"; "salut"]
\end{verbatim}
\afterverb
When you add twice, the most recent add is what will be used, unless
you use a function that specifically works with all the values, such 
as {\tt \verb"find_all"}, which returns a list of all values. {\tt replace} 
and {\tt remove}, however, only work on the most recent value - so
if you remove a second value, you'll now be working with the first.

The {\tt length} function returns the number of mappings (not necessarily
the number of keys):

\beforeverb
\begin{verbatim}
# Hashtbl.length eng2fr
- : int = 2
\end{verbatim}
\afterverb

To check whether or not something is a key in a hashtable, use the {\tt mem}
function:

\beforeverb
\begin{verbatim}
# Hashtbl.mem eng2fr "hello";;
- : bool = true
\end{verbatim}
\afterverb

\index{membership!hashtable}

When finding items in a list, the amount of time it took to find an element
grew proportionally to the length of that list. For remarkable reasons I won't
explain, this isn't true for hashtables - it takes about the same amount of time
to find a given element no longer how large the hashtable is!

\index{hashtable}

\begin{ex}
\label{wordlist2}

\index{set membership}
\index{membership!set}

For this exercise, we need a list of English words.
There are lots of word lists available on the Web, but the one most
suitable for our purpose is one of the word lists collected and
contributed to the public domain by Grady Ward as part of the Moby
lexicon project\footnote{\url{wikipedia.org/wiki/Moby_Project}.}.  It
is a list of 113,809 official crosswords; that is, words that are
considered valid in crossword puzzles and other word games.  In the
Moby collection, the filename is {\tt 113809of.fic}; I host a copy
of this file, with the simpler name {\tt words.txt}, at {\url www.thinkocaml.com/bin/words.txt}.

\index{word list}
\index{words.txt}

Write a function that reads the words in {\tt words.txt} and
stores them as keys in a hashtable.  It doesn't matter what the
values are.  Then you can use the {\tt mem} function
as a fast way to check whether a string is in
the hashtable.

If you did Exercise~\ref{wordlist1}, you can compare the speed
of this implementation with the list equivalent.

\end{ex}


\section{Hashtable as a set of counters}
\label{histogram}

\index{counter}

Suppose you are given a string and you want to count how many
times each letter appears.  There are several ways you could do it:

\begin{enumerate}

\item You could create 26 variables, one for each letter of the
alphabet.  Then you could traverse the string and, for each
character, increment the corresponding counter, probably using
pattern matching.

\item You could create a list with 26 elements.  Then you could
convert each character to a number, use the number as an index 
into the list, and increment the appropriate counter.

\item You could create a hashtable with characters as keys
and counters as the corresponding values.  The first time you
see a character, you would add an item to the dictionary.  After
that you would increment the value of an existing item.

\end{enumerate}

Each of these options performs the same computation, but each
of them implements that computation in a different way.

\index{implementation}

An {\bf implementation} is a way of performing a computation;
some implementations are better than others.  For example,
an advantage of the dictionary implementation is that we don't
have to know ahead of time which letters appear in the string
and we only have to make room for the letters that do appear.

Here is what the code might look like:

\beforeverb
\begin{verbatim}
#load "str.cma";;

let histogram s = 
	let wordlist = Str.split (Str.regexp "\\b ") s in
	let hist = Hashtbl.create 1 in
	let addfunct e = 
		if (Hashtbl.mem hist e)
		then let cntr = (Hashtbl.find hist e + 1)
			in Hashtbl.replace hist e cntr
		else Hashtbl.add hist e 1
	in
	List.iter addfunct wordlist;
	hist
;;
\end{verbatim}
\afterverb
%
This function takes a string, splits it into words, and then creates a 
hashtable with the words as keys and the number of times that word 
appeared as values. The name of the function is {\bf histogram}, which 
is a statistical term for a set of counters (or frequencies).

\index{histogram}
\index{frequency}

The first line of the function creates an empty Hashtable, with assumed 
length of 1. If you know more information about the string you're going 
to pass to histogram, you might pass a more intelligent guess. It then 
iterates over the list, for each element either adding the previously-unseen
element to the hashtable, or else increasing the counter for that 
element by one.

\index{histogram}

Here's how it works:

\beforeverb
\begin{verbatim}
let histprint tbl = 
	Hashtbl.iter (fun key value ->
			print_string (key^":"^(string_of_int value)^"\n"))
		tbl;;
		
let hist = histogram "hello day, the sun says hello";;

# histprint hist;;
sun:1
the:1
says:1
hello:2
day,:1
- : unit = ()
\end{verbatim}
\afterverb
%
The histogram indicates that ``sun'', ``the'', and ``says'' all appear once, and hello appears twice. Note that it doesn't really handle punctuation the way we'd probably want it to, so the word ``day,'' appears once, not just the word ``day''.

\begin{ex}
Rewrite {\tt histogram} to better handle punctuation. If you did the exercises in chapter \ref{chap:regex}, this should be easy for you.
\end{ex}

\section{Iteration and Hashtables}

\index{dictionary!looping with}
\index{looping!with dictionaries}
\index{traversal}

We just saw an instance of using iteration over hashtables. Let's break it down a little more:

\beforeverb
\begin{verbatim}
let histprint tbl = 
	Hashtbl.iter (fun key value ->
			print_string (key^":"^(string_of_int value)^"\n"))
		tbl;;

# histprint hist;;
sun:1
the:1
says:1
hello:2
day,:1
- : unit = ()
\end{verbatim}
\afterverb

Iteration in hashtables works not unlike that of lists and arrays.
The only real difference is that the function argument takes two 
arguments - first the key and then the value.

\begin{ex}

Modify \verb"print_hist" to print the keys and their values
in alphabetical order.

\end{ex}

\section{Folding and Hashtables}

You can also fold hashtables, which, again, is kind of what you
would expect. Let's say we wanted to add up the number of words 
in our histogram that begin with the letter s:

\beforeverb
\begin{verbatim}
let addSes tbl = 
	Hashtbl.fold (fun key value acc -> 
			if key.[0] = 's'
			then acc+value
			else acc)
			tbl 0 ;;
\end{verbatim}
\afterverb

One thing to note, there is no {\tt \verb"fold_left"} or {\tt \verb"fold_right"}
for hashtables. This is because the mappings in the hashtable are not stored in 
a particular order.

\section{Reverse lookup}

\index{dictionary!lookup}
\index{dictionary!reverse lookup}
\index{lookup, dictionary}
\index{reverse lookup, dictionary}

Given a dictionary {\tt d} and a key {\tt k}, it is easy to
find the corresponding value {\tt v = d[k]}.  This operation
is called a {\bf lookup}.

But what if you have {\tt v} and you want to find {\tt k}?
You have two problems: first, there might be more than one
key that maps to the value {\tt v}.  Depending on the application,
you might be able to pick one, or you might have to make
a list that contains all of them.  Second, there is no
simple syntax to do a {\bf reverse lookup}; you have to search.

Here is a function that takes a value and returns a reference list of 
keys :

\beforeverb
\begin{verbatim}
let reverse_lookup tbl v = 
	let lst = ref [] in
	Hashtbl.iter
		(fun key value ->
			if value==v
			then lst := key::!lst )
		tbl;
	lst;;
\end{verbatim}
\afterverb



Here is an example of a successful reverse lookup:

\beforeverb
\begin{verbatim}
# let hist = histogram "hello day the sun says hello";;
# reverse_lookup hist 1;;
- : string list ref = {contents = "says"; "day"; "the"; "sun"}
\end{verbatim}
\afterverb
%
Note again how they are out of order.

And a couple unsuccessful ones:

\beforeverb
\begin{verbatim}
# reverse_lookup hist 3;;
- : string list ref = {contents = []}
# reverse_lookup hist 'a';;
Error: This expression has type char but an expression was expected of type int
\end{verbatim}
\afterverb
%
In some situations, this is probably the behavior you want: an error if the lookup is impossible, and an empty list if there are no keys. However, it's also possible that you'd want to raise an error if a key isn't found, rather than letting the program go on with an empty list. For this, there's the {\tt exception} and {\tt raise} functions:

\beforeverb
\begin{verbatim}
exception UnfoundValue;;

let reverse_lookup tbl v = 
	let lst = ref [] in
	Hashtbl.iter
		(fun key value ->
			if value==v
			then lst := key::!lst )
		tbl;
	match !lst with
		[] -> raise UnfoundValue
		| h::t -> ();
	!lst;;
\end{verbatim}
\afterverb
{\tt exception} defines a cnew exception. Note that the argument isn't exactly a string - it is not between quotes. This is actually a new type we haven't seen before, namely that of an exception. We can then raise this exception with the {\tt raise} function.

Now, when we run the search with a value that doesn't exist, it will throw an exception error:

\beforeverb
\begin{verbatim}
# reverse_lookup hist 3;;
Exception: UnfoundValue
\end{verbatim}
\afterverb

You should always try to name exceptions such that they will make sense to your user. Remember that whoever else works with your code can't read your brain. Be nice to them.

In general, a reverse lookup is much slower than a forward lookup; if you
have to do it often, or if the dictionary gets big, the performance
of your program will suffer.

\begin{ex}
Modify \verb"reverse_lookup" so that it returns only the first key that points to the value, then so it points to the greatest-valued (in the built-in {\tt compare} function sense) key.
\end{ex}

\section{Memos}
If you wrote and played with the {\tt fibonacci} function from
Exercise~\ref{ex:fibonacci}, you probably wrote a function that looks something like this:
\beforeverb
\begin{verbatim}
let rec fibonacci n = match n with
	x when x=0 -> 0
	| x when x=1 -> 1
	| x -> (fibonacci (n-1)) + (fibonacci (n-2));;
\end{verbatim}
\afterverb
and you might have noticed that the bigger
the argument you provide, the longer the function takes to run.
Furthermore, the run time increases very quickly. This is because the
number of function calls required grows exponentially with each call.

\index{fibonacci function}
\index{function!fibonacci}

In particular, consider how many times {\tt fibonacci(0)} and {\tt fibonacci(1)} 
are called. This is an inefficient solution to the problem, and it gets
worse as the argument gets bigger.

\index{memo}

One solution is to keep track of values that have already been
computed by storing them in a dictionary.  A previously computed value
that is stored for later use is called a {\bf memo}\footnote{See
  \url{wikipedia.org/wiki/Memoization}.}.  Here is an
implementation of {\tt fibonacci} using memos:

\beforeverb
\begin{verbatim}
let known = Hashtbl.create 2;;
Hashtbl.add known 0 1;;
Hashtbl.add known 1 1;;
let rec fibonacci n =
	if Hashtbl.mem known n
	then Hashtbl.find known n
	else let fn = (fibonacci (n-1)) + (fibonacci (n-2)) in
		Hashtbl.add known n fn;
		fn;;

let printknown () = 
	let n = ref 0 in
	while Hashtbl.mem known !n do
		print_string ("f("^(string_of_int !n)^"):"^
			(string_of_int (Hashtbl.find known !n)));
		print_newline ();
		n := !n+1
	done;;
\end{verbatim}
\afterverb
%
{\tt known} is a hashtable that keeps track of the Fibonacci
numbers we already know.  It starts with
two items: 0 maps to 0 and 1 maps to 1.

Whenever {\tt fibonacci} is called, it checks {\tt known}.
If the result is already there, it can return
immediately.  Otherwise it has to 
compute the new value, add it to the hashtable, and return it. 
Thus, we build up a record of all the fibonacci numbers up to 
a highest call. We can view our record by calling {\tt printknown}:

\beforeverb
\begin{verbatim}
# fibonacci 10;;
- : int = 89http://en.literateprograms.org/Fibonacci_numbers_(OCaml)#Arbitrary_Precision
# printknown();;
f(0):0
f(1):1
f(2):2
f(3):3
f(4):5
f(5):8
f(6):13
f(7):21
f(8):34
f(9):55
f(10):89
\end{verbatim}
\afterverb

\begin{ex}
Run this version of {\tt fibonacci} and the original with
a range of parameters and compare their run times.
\end{ex}

In the previous example, {\tt known} is created outside the function,
so it belongs to the special frame that is the highest scope.
Variables in this scope are sometimes called {\bf global}
because they can be accessed from any function.  Unlike local
variables, which disappear when their function ends, global variables
persist from one function call to the next. They are an example of using 
scope to your advantage, but you must always be careful when using scope.

\section{Long integers}

\index{long integer}
\index{integer!long}
\index{type!long}

If I compute {\tt fibonacci(50)}, I get:

\beforeverb
\begin{verbatim}
>>> fibonacci(50)
- : int=1037658242
\end{verbatim}
\afterverb
%
which isn't too suspicious. It's the wrong answer, but it gets worse. Let's look at the record 
and see:

\beforeverb
\begin{verbatim}
...
f(48):-811192543
f(49):-298632863
f(50):1037658242
\end{verbatim}
\afterverb
Well, that doesn't look good at all. the 48-th and 49-th term are clearly not right, and they also clearly don't add up to f(50). Values with type {\tt int} have a limited range, which we've exceeded. There are ways around this problem, but I won't bother with them here. If you want to find out more, I recommend looking at \url{http://en.literateprograms.org/Fibonacci_numbers_(OCaml)#Arbitrary_Precision}.

\begin{ex}

\index{encryption}
\index{RSA algorithm}
\index{algorithm!RSA}

Exponentiation of large integers is the basis of common
algorithms for public-key encryption.  Read the Wikipedia
page on the RSA algorithm\footnote{\url{wikipedia.org/wiki/RSA}.}
and write functions to encode and decode messages.

\end{ex}


\section{Debugging}
\index{debugging}
%write here
As you work with bigger datasets it can become unwieldy to
debug by printing and checking data by hand.  Here are some
suggestions for debugging large datasets:

\begin{description}

\item[Scale down the input:] If possible, reduce the size of the
dataset.  For example if the program reads a text file, start with
just the first 10 lines, or with the smallest example you can find.
You can either edit the files themselves, or modify the
program so it reads only the first {\tt n} lines.

If there is an error, you can reduce {\tt n} to the smallest
value that manifests the error, and then increase it gradually
as you find and correct errors.

\item[Check summaries and types:] Instead of printing and checking the
entire dataset, consider printing summaries of the data: for example,
the number of items in a dictionary or the total of a list of numbers.

A common cause of runtime errors is a value that is not the right
type.  For debugging this kind of error, it is often enough to print
the type of a value.

\item[Write self-checks:]  Sometimes you can write code to check
for errors automatically.  For example, if you are computing the
average of a list of numbers, you could check that the result is
not greater than the largest element in the list or less than
the smallest.  This is called a ``sanity check'' because it detects
results that are ``insane.''

\index{sanity check}
\index{consistency check}

Another kind of check compares the results of two different
computations to see if they are consistent.  This is called a
``consistency check.''

\item[Pretty print the output:] Formatting debugging output
can make it easier to spot an error. Writing (or, better yet,
finding built-in or distributed) functions to print things in
human-readable ways can make your life a lot easier.

\index{pretty print}
\index{pprint module}
\index{module!pprint}

\end{description}

Again, time you spend building scaffolding can reduce
the time you spend debugging.

\index{scaffolding}

\section{Glossary}

\begin{description}

\item[hashtable:] A mapping from a set of keys to their
corresponding values.
\index{hashtable}

\item[key-value pair:] The representation of the mapping from
a key to a value.
\index{key-value pair}

\item[item:] Another name for a key-value pair.
\index{item!hashtable}

\item[key:] An object that appears in a hashtable as the
first part of a key-value pair.
\index{key}

\item[value:] An object that appears in a hashtable as the
second part of a key-value pair.  This is more specific than
our previous use of the word ``value.''
\index{value}

\item[implementation:] A way of performing a computation.
\index{implementation}

\item[hashtable:] The algorithm used to implement Python
hashtables.
\index{hashtable}

\item[hash function:] A function used by a hashtable to compute the
location for a key.
\index{hash function}
% 
% \item[hashable:] A type that has a hash function.  Immutable
% types like integers,
% floats and strings are hashable; mutable types like lists and
% dictionaries are not.
% \index{hashable}

\item[lookup:] A hashtable operation that takes a key and finds
the corresponding value.
\index{lookup}

\item[reverse lookup:] A hashtable operation that takes a value and finds
one or more keys that map to it.
\index{reverse lookup, hashtable}
% 
% \item[singleton:] A list (or other sequence) with a single element.
% \index{singleton}
% 
% \item[call graph:] A diagram that shows every frame created during
% the execution of a program, with an arrow from each caller to
% each callee. 
% \index{call graph}
% \index{diagram!call graph}

\item[histogram:] A set of counters.
\index{histogram}

\item[memo:] A computed value stored to avoid unnecessary future 
computation.
\index{memo}

\item[global variable:]  A variable defined outside a function.  Global
variables can be accessed from any function.
\index{global variable}

\item[flag:] A boolean variable used to indicate whether a condition
is true.
\index{flag}

\item[declaration:] A statement like {\tt global} that tells the
interpreter something about a variable.
\index{declaration}

\end{description}

\section{Exercises}

\begin{ex}
\index{duplicate}

If you did Exercise~\ref{duplicate}, you already have
a function named \verb"has_duplicates" that takes a list
as a parameter and returns {\tt True} if there is any object
that appears more than once in the list.

Use a dictionary to write a faster, simpler version of
\verb"has_duplicates".
\end{ex}


\begin{ex}
\label{exrotatepairs}

\index{letter rotation}
\index{rotation!letters}

Two words are ``rotate pairs'' if you can rotate one of them
and get the other (see \verb"rotate_word" in Exercise~\ref{exrotate}).

Write a program that reads a wordlist and finds all the rotate
pairs.
\end{ex}


\begin{ex}
\index{Car Talk}
\index{Puzzler}

Here's another Puzzler from {\em Car
Talk}\footnote{\url{www.cartalk.com/content/puzzler/transcripts/200717}.}:

\begin{quote}
This was sent in by a fellow named Dan O'Leary. He came upon a common
one-syllable, five-letter word recently that has the following unique
property. When you remove the first letter, the remaining letters form
a homophone of the original word, that is a word that sounds exactly
the same. Replace the first letter, that is, put it back and remove
the second letter and the result is yet another homophone of the
original word. And the question is, what's the word?

Now I'm going to give you an example that doesn't work. Let's look at
the five-letter word, `wrack.' W-R-A-C-K, you know like to `wrack with
pain.' If I remove the first letter, I am left with a four-letter
word, 'R-A-C-K.' As in, `Holy cow, did you see the rack on that buck!
It must have been a nine-pointer!' It's a perfect homophone. If you
put the `w' back, and remove the `r,' instead, you're left with the
word, `wack,' which is a real word, it's just not a homophone of the
other two words.

But there is, however, at least one word that Dan and we know of,
which will yield two homophones if you remove either of the first two
letters to make two, new four-letter words. The question is, what's
the word?
\end{quote}

\index{homophone}
\index{reducible word}
\index{word, reducible}

You can use the dictionary from Exercise~\ref{wordlist2} to check
whether a string is in the word list.

To check whether two words are homophones, you can use the CMU
Pronouncing Dictionary.  You can download it from
\url{www.speech.cs.cmu.edu/cgi-bin/cmudict}.

Write a program that lists all the words that solve the Puzzler.

\end{ex}



\chapter{Tuples}
\label{tuplechap}

\index{tuple}
\index{type!tuple}
\index{sequence}

A tuple is an immutable sequence of values, not unlike lists. The important difference is that tuples can contain objects of any type.

\section{Creating and Using Tuples}

Syntactically, a tuple is a comma-separated list of values:

\beforeverb
\begin{verbatim}
# let t = 'a', 'b', 'c', 'd', 'e';;
val t : char * char * char * char * char = ('a', 'b', 'c', 'd', 'e')
\end{verbatim}
\afterverb
%
Note that the ocaml interpreter prints the type of a tuple as a series of types connected by asterisks. Although it is not necessary, it is common to enclose tuples in
parentheses:

\index{parentheses!tuples in}

\beforeverb
\begin{verbatim}
# let t = ('a', 'b', 'c', 'd', 'e');;
\end{verbatim}
\afterverb
%
If you're passing a tuple as an argument, however, it does need to be enclosed in parentheses to tell the function how to group it.

Much like lists, there's no built-in way to access the elements of a tuple in general. If your tuple is a pair, you can use the {\tt fst} and {\tt snd} functions to access the first and second elements, respecitvely, but for larger tuples you'll need to write your own functions, or use arrays instead. Unlike lists, there isn't the idea of a tuple ``head'' and ``tail,'' either. In general, you need to use pattern matching to select elements of a tuple:

\beforeverb
\begin{verbatim}
# let third_of_three trip = match trip with (_,_,x) -> x;;
val third_of_three 'a * 'b * 'c -> 'c = <fun>
# third_of_three (1,2,3);;
- : int = 3
\end{verbatim}
\afterverb

\section{Tuple assignment}
\label{tuple assignment}

\index{tuple!assignment}
\index{assignment!tuple}
\index{swap pattern}
\index{pattern!swap}

It is often useful to swap the values of two variables.
With conventional assignments, you have to use a temporary
variable.  For example, to swap {\tt a} and {\tt b}:

\beforeverb
\begin{verbatim}
# let temp = a;;
# let a = b;;
# let b = temp;;
\end{verbatim}
\afterverb
%
This solution is quite combersome, and wastes precious memory. This can more cleanly be accomplished with an {\tt and}:

\beforeverb
\begin{verbatim}
#let a = b and b = a;;
\end{verbatim}
\afterverb

but that's a little cumbersome, too. This can be made much cleaner using {\bf tuple assignment}:

\beforeverb
\begin{verbatim}
# let a, b = b, a;;
\end{verbatim}
\afterverb
%
The left side is a tuple of variables; the right side is a tuple of
expressions.  Each value is assigned to its respective variable.  
All the expressions on the right side are evaluated before any
of the assignments.

The number of variables on the left and the number of
values on the right have to be the same:

\index{exception!ValueError}
\index{ValueError}

\beforeverb
\begin{verbatim}
# let a, b = 1, 2, 3;;
Error: This expression has type int * int * int
       but an expression was expected of type 'a * 'b
\end{verbatim}
\afterverb
%

\section{Tuples as return values}

\index{tuple}
\index{value!tuple}
\index{return value!tuple}
\index{function, tuple as return value}

Strictly speaking, a function can only return one value, but
if the value is a tuple, the effect is the same as returning
multiple values.  For example, if you want to divide two integers
and compute the quotient and remainder, it makes sense to do it in 
one fell swoop:

\beforeverb
\begin{verbatim}
# let divmod a b = a/b, a mod b;;
# divmod 5 2;;
- : int * int = (2, 1)
\end{verbatim}
\afterverb
%
Or use tuple assignment to store the elements separately:

\index{tuple assignment}
\index{assignment!tuple}

\beforeverb
\begin{verbatim}
# let quot, rem = divmod(5, 2)
val q : int = 2
val r : int = 1
\end{verbatim}
`\afterverb

\section{Lists and tuples}

\index{zip function}
\index{function!zip}

{\tt List.combine} is a built-in function that takes two lists and
combines them into a list of tuples where each tuple contains one 
element from each sequence.

This example combines a list of ints and a list of chars:

\beforeverb
\begin{verbatim}
# let c = ['a'; 'b'; 'c'];;
# let t = [0, 1, 2];;
# List.combine t c;;
- : (int * char) list = [(1, 'a') (2, 'b') (3, 'c')]
\end{verbatim}
\afterverb
%
The result is a list of tuples where each tuple contains
an integer and a char.

\index{list!of tuples}

You can use tuple assignment and recursion to traverse a list of
tuples:

\index{traversal}
\index{tuple assignment}
\index{assignment!tuple}

\beforeverb
\begin{verbatim}
let print_tuple tup = 
	let t, c = tup in
		print_string "(";
		print_int t;
		print_string ", ";
		print_char c;
		print_string")";
		print_newline ();;

let rec tuplister tlst = match tlst with 
	[] -> ()
	| h::t -> print_tuple h;
		tuplister t;;

# let tlist = [(1, 'a'); (2, 'b'); (3, 'c')];;
# tuplister tlist;;
(1, 'a')
(2, 'b')
(3, 'c')
- : unit = () 
\end{verbatim}
\afterverb

\begin{ex}
Most of these methods have equivalent or similar functions for Arrays. You should look them up in the Array module and play with them, too.
\end{ex}

\section{Comparing tuples}

\index{comparison!tuple}
\index{tuple!comparison}

The relational operators work with tuples;
OCaml starts by comparing the first element from each
sequence.  If they are equal, it goes on to the next elements,
and so on, until it finds elements that differ.  Subsequent
elements are not considered (even if they are really big).

\beforeverb
\begin{verbatim}
# (0, 1, 2) < (0, 3, 4);;
- : bool = true
# (0, 1, 2000000) < (0, 3, 4);;
- : bool = true
\end{verbatim}
\afterverb

\section{Debugging}

\section{Glossary}

\section{Exercises}

\chapter{Records and Custom Data Structures}

Records are very similar to tuples in that they're ordered sets of information of any type. Records, however, are labelled - each piece of information gets a title. They are also custom-defined types: you have to tell OCaml ahead of time what the record is going to look like. You do this by using the {\tt type} keyword:

\beforeverb
\begin{verbatim}
# type identity = {
  firstName: string;
  lastName: string; 
  sex: char; 
  age: int
};;
type identity = {
  firstName : string;
  lastName : string;
  sex : char;
  age : int;
}
\end{verbatim}
\afterverb

We can now create a record of the type {\tt identity} like so:

\beforeverb
\begin{verbatim}
let nmonje = {firstName = "Nicholas"; lastName = "Monje"; sex = 'm'; age = 21}
\end{verbatim}
\afterverb
\section{Tuples}

We can access elements of a record using dot syntax:

\beforeverb
\begin{verbatim}
# nmonje.age;;
- : int = 21
\end{verbatim}
\afterverb

Record comparison works the same way as tuple comparison - it compares 
elements in order and returns a value based on the first different element:

\beforeverb
\begin{verbatim}
type pair = {x: int; y: int};;
let a = {x = 1; y = 2};;
let b = {x = 2; y = 2};;
let c = {x = 1; y = 3};;
let d = {x = 1; y = 2};;
# a<b
- : bool = true
# a<c
- : bool = true
# b<c
- : bool = false
# a = d
- : bool = true
# a == d
- : bool = false
\end{verbatim}
\afterverb

Wait, what? {\tt a} and {\tt d} are ``{\tt =}'' but not ``{\tt ==}''? What does that mean?

The single equals sign tests for what's called {\bf structural} or {\bf deep equality}, or tests to see if two objects' contents are the same. The double equals sign tests for {\bf physical} or {\bf shallow equality}, or whether or not two objects reference the same thing. In most of what we've seen so far, the two are equivalent. If they simply point to integers, then the two equalities effectively mean the same thing. However, now that we're looking at more ``object-y'' objects, there can be a subtle difference. For example, two references are not necessarily shallowly equivalent:

\beforeverb
\begin{verbatim}
# let x = ref 10;;
# let y = ref 10;;
# x = y;;
- : bool = true
# x == y;;
- : bool = false
\end{verbatim}
\afterverb

{\tt x} and {\tt y} have the same value, but they point to two different spots in the computer's memory, so they are not shallowly equivalent. It's perhaps a little bit weird that two things are deeply equivalent but not shallowly equivalent, but just think of it like people: we're different on the outside, but deep down we're all the same. Or something like that.

\section{Enumerated Types}

The {\tt type} keyword isn't just for records. It can be used to define many different kinds of types. One important custom type is called an {\bf enumerated type}, which has a discrete, finite set of values:

\beforeverb
\begin{verbatim}
# type enum = A | B | C';
type enum = A | B | C
# let a = A;;
val a : enum = A
# let d = D;;
Error: Unbound constructor D
\end{verbatim}
\afterverb

The newly-defined {\tt enum} type has three possible values - A, B, or C. This example isn't particularly interesting, but there isn't a whole lot built-in around enumerated types - or any enumerated type, really. They're entirely custom-defined, and you must write code to interact with them.

There is implicit comparison, though, determined by the order in which you defined the type:

\beforeverb
\begin{verbatim}
# A < B;;
- : bool = true
# C > B;;
- : bool = true
# A > C;;
- : bool = false
\end{verbatim}
\afterverb

\section{Aggregate types}

Next, you can define your own {\bf aggregate types}, which are types that are composed of basic types:

\beforeverb
\begin{verbatim}
# type agg = Agg of int * string;;
# let a = Agg (1, "hi");;
val a : agg = Agg (1, "hi")
\end{verbatim}
\afterverb

Aggregate types can be enumerated, and can be recursive. Here's a basic definition of a tree of integers:

\beforeverb
\begin{verbatim}
type tree = Tree of int * tree | Leaf of int
\end{verbatim}
\afterverb

which would allow us to define the following tree:

\beforeverb
\begin{verbatim}
let t = Tree (3, Tree( 2, Leaf 1));;
\end{verbatim}
\afterverb

This tree is, of course, not very interesting because it can't branch. We can quite easily create a binary tree:

\beforeverb
\begin{verbatim}
type bitree = Tree of int * tree * tree | Leaf of int | Null;;
\end{verbatim}
\afterverb

The Null allows us to make this tree not full - if we don't want to branch in both directions, we could make one direction be Null. We could furhter expand this definition to any determined finite size tree. However, if we want to leave the number of nodes ambiguous, we could use a list of trees:

\beforeverb
\begin{verbatim}
type mtree = Tree of int * mtree list | Leaf of int | Null;;
let mt = Tree (3, [Tree (2, [Null]); Tree (2, [Tree (1, [Leaf 1])])]);;
\end{verbatim}
\afterverb

Which of course is kind of nasty because {\it every} node must be a list, even if it contains only one element, which you could easily get around by including another enumeration for {\tt Tree of int* mtree}. Even then, this is where parentheses matching can get very important. You might want to consider finding a development environment that will help you with that.

Of course, all these enumerated types only work on integers. We can also define our tree to be polymorphic. I'm going to stick to a binary tree for this example:

\beforeverb
\begin{verbatim}
type 'a ptree = PTree of 'a * 'a ptree * 'a ptree | PLeaf of 'a | PNull;;

let pt = PTree ("Root", PTree ("Node", PLeaf "Leaf", PLeaf "Leaf"), PLeaf "Leaf");;
\end{verbatim}
\afterverb

Of course, in this example, all the data must be of the same type.

\begin{ex}
Rewrite the polymorphic tree example above such that it can store data of two different types. Note that different polymorphic types are written as {\tt 'a}, {\tt 'b}, and so on. 
\end{ex}


\section{Debugging}

\index{debugging}


One thing to be careful of is redefining types. For example:

%write here

\section{Glossary}

\begin{description}

\item[tuple:] An immutable sequence of elements which may be of different types.
\index{tuple}

\item[tuple assignment:] An assignment with a sequence on the
right side and a tuple of variables on the left.  The right
side is evaluated and then its elements are assigned to the
variables on the left.
\index{tuple assignment}
\index{assignment!tuple}

\item[gather:] The operation of assembling a variable-length
argument tuple.
\index{gather}

\item[scatter:] The operation of treating a sequence as a list of
arguments.
\index{scatter}

\item[DSU:] Abbreviation of ``decorate-sort-undecorate,'' a
pattern that involves building a list of tuples, sorting, and
extracting part of the result.
\index{DSU pattern}

\item[data structure:] A collection of related values, often
organized in lists, dictionaries, tuples, etc.
\index{data structure}

\item[shape (of a data structure):] A summary of the type,
size and composition of a data structure.
\index{shape}

\end{description}


\section{Exercises}
%write here
\begin{ex}
Write a function called \verb"most_frequent" that takes a string and
prints the letters in decreasing order of frequency.  Find text
samples from several different languages and see how letter frequency
varies between languages.  Compare your results with the tables at
\url{wikipedia.org/wiki/Letter_frequencies}.

\index{letter frequency}
\index{frequency!letter}

\end{ex}


\begin{ex}
\label{anagrams}

\index{anagram set}
\index{set!anagram}

More anagrams!

\begin{enumerate}

\item Write a program
that reads a word list from a file and
prints all the sets of words that are anagrams.

Here is an example of what the output might look like:

\beforeverb
\begin{verbatim}
['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']
['retainers', 'ternaries']
['generating', 'greatening']
['resmelts', 'smelters', 'termless']
\end{verbatim}
\afterverb
%
Hint: you might want to build a dictionary that maps from a
set of letters to a list of words that can be spelled with those
letters.  The question is, how can you represent the set of
letters in a way that can be used as a key?

\item Modify the previous program so that it prints the largest set
of anagrams first, followed by the second largest set, and so on.

\index{Scrabble}
\index{bingo}

\item In Scrabble a ``bingo'' is when you play all seven tiles in
your rack, along with a letter on the board, to form an eight-letter
word.  What set of 8 letters forms the most possible bingos?
Hint: there are seven.

% (7, ['angriest', 'astringe', 'ganister', 'gantries', 'granites',
% 'ingrates', 'rangiest'])

\index{metathesis}

\item Two words form a ``metathesis pair'' if you can transform one
  into the other by swapping two letters\footnote{This exercise is
    inspired by an example at \url{puzzlers.org}.}; for example,
  ``converse'' and ``conserve.''  Write a program that finds all of
  the metathesis pairs in the dictionary.  Hint: don't test all pairs
  of words, and don't test all possible swaps.
% 
% You can download a solution from \url{thinkpython.com/code/anagram_sets.py}.
% 
\end{enumerate}
\end{ex}



\begin{ex}

\index{Car Talk}
\index{Puzzler}

Here's another Car Talk Puzzler\footnote{
\url{www.cartalk.com/content/puzzler/transcripts/200651}.}:

\begin{quote}
What is the longest English word, that remains a valid English word,
as you remove its letters one at a time?

Now, letters can be removed from either end, or the middle, but you
can't rearrange any of the letters. Every time you drop a letter, you
wind up with another English word. If you do that, you're eventually
going to wind up with one letter and that too is going to be an
English word---one that's found in the dictionary. I want to know
what's the longest word and how many letters does it
have?

I'm going to give you a little modest example: Sprite. Ok? You start
off with sprite, you take a letter off, one from the interior of the
word, take the r away, and we're left with the word spite, then we
take the e off the end, we're left with spit, we take the s off, we're
left with pit, it, and I.
\end{quote}

\index{reducible word}
\index{word, reducible}

Write a program to find all words that can be reduced in this way,
and then find the longest one.

This exercise is a little more challenging than most, so here are
some suggestions:

\begin{enumerate}

\item You might want to write a function that takes a word and
  computes a list of all the words that can be formed by removing one
  letter.  These are the ``children'' of the word.

\index{recursive definition}
\index{definition!recursive}

\item Recursively, a word is reducible if any of its children
are reducible.  As a base case, you can consider the empty
string reducible.

\item The wordlist I provided, {\tt words.txt}, doesn't
contain single letter words.  So you might want to add
``I'', ``a'', and the empty string.

\item To improve the performance of your program, you might want
to memoize the words that are known to be reducible.

\end{enumerate}

% You can see my solution at \url{thinkpython.com/code/reducible.py}.
% 
\end{ex}


\chapter{Putting the O in Ocaml Part 2: Objects and Classes}

In general, OCaml programming (and programmers) prefer function-oriented programming, and you generally can - and should - use primarily functional solutions to programming. However, object-oriented programming can be very useful in certain situations.

Object-oriented programming with objects would be just oriented programming, and that's not very fun. Objects can take many forms, so the closest thing we can get to a definition is an object is something a variable points to that has a type and value, and possibly methods. What this means will make more sense with an example.

Go to \url{inserturlhere} and download {\tt oturtle.zip}. Unzip the files using your favorite archive software.\footnote{I recommend 7zip for Windows.}

Now, open the interpreter in the same directory and type {\tt \#use "oturtle.ml"}. You can now call functions defined within the Oturtle module. You'll better understand  what's going on here later. Note that this loads the very useful {\tt Graphics} module as well. You should briefly check out this module online.
%note to self: get oturtle working as standard module.

What Oturtle does is facilitates a particular method of drawing. Namely, we have turtles, which can draw along their path.\footnote{The reason it's a turtle is of course whimsical.} We can control the turtle by telling it to move, and draw as it goes along (we can also tell it to move {\it without} drawing).

\section{Turtles}

Now that we conceptually understand what Oturtle does, open a blank figure with {\tt Oturtle.init ()}.

We can now create a turtle like so:

\beforeverb
\begin{verbatim}
# let bob = new Oturtle.turtle;;
\end{verbatim}
\afterverb

This is a syntax we haven't seen before. We've created a variable, {\tt bob} which refers to an object, namely a turtle. The keyword {\tt new} tells us to create a new object of the specified type (without it, bob would point to the type, or {\bf class} itself). The new turtle is of a random color and exists

Now, let's see what Bob looks like. In order to draw Bob, we can call the {\tt draw} {\bf method}. A method is a like a function, but it is written into the definition of an object and it is kind of like the object is doing something. The syntax is quite unlike what we've seen before:

\beforeverb
\begin{verbatim}
# bob#draw;;
\end{verbatim}
\afterverb

And Bob shows up in the middle of the canvas! Isn't he cute? Note that this method does not take an argument - not even the unit argument, like all functions we've seen. A method {\it can} take an argument, and we'll see that in a second, but it's not necessary. There is currently no method of erasing bob, so he'll always show up right there, even after we've moved him someplace else. This functionality will hopefully be implemented in a later version.
%note to self: implement this

Now, that's adorable, but Bob wouldn't be a very good turtle if he couldn't move. Perhaps unsurprisingly, telling Bob to move is also a method. In fact, there are two methods: {\tt step}, which moves a single pixel, and {\tt advance}, which takes an integer argument and moves Bob that many pixels.

\beforeverb
\begin{verbatim}
# bob#step;;
# bob#draw;;
# bob#advance 100;;
# bob#draw;;
\end{verbatim}
\afterverb

You'll notice that a pixel isn't very far - he barely looks like he's moved at all!

You can also tell Bob to turn:

\beforeverb
\begin{verbatim}
# bob#turn 90;;
# bob#advance 30;;
# bob#draw;;
\end{verbatim}
\afterverb

{\tt turn} also takes an integer argument and rotates Bob that many degrees. If you're not familiar with degrees of a circle, you should read about them on wikipedia.

We can tell Bob to start drawing by lowering his pen, or stop drawing by telling him to raise his pen:

\beforeverb
\begin{verbatim}
bob#lower_pen;;
bob#advance 100;;
bob#draw;;
bob#raise_pen;;
bob#advance 30;;
bob#draw;;
\end{verbatim}
\afterverb

When the pen is lowered, the turtle draws a line along his path. When the pen is raised, it doesn't.

Besides, methods, objects also have values. Values preserve the state of the object - without values, an object doesn't contain any information. Values can be either mutable or immutable, depending on whether you set them to be or not (values are by default immuatble. A turtle, for example, has mutable values x and y coordinates {\tt x} and {\tt y}, direction {\tt theta}, all integers as well as a an immutable color {\tt color}, which is a special type {\tt Graphics.color}, as well as pen status {\tt pen}, which is a custom enumerated type with values {\tt Raised} and {\tt Lowered}.

In general, OCaml doesn't provide a way to acces values of an object. Methods, as we have already seen, can change the values of mutable values - {\tt advance}, {\tt step}, and {\tt turn} all change Bob's values. There are also often methods which return values:

\beforeverb
\begin{verbatim}
# bob#get_pos;;
- : int * int = (400, 254)
# bob#get_dir;;
- : int = 90
\end{verbatim}
\afterverb

These functions don't change values (though a method can both change and return a value), but they do read and return values.

\begin{ex}
%write here
\end{ex}

\section{Defining Modules and Classes}

Now, let's lift the hood on this code a little bit. Open {\tt oturtle.ml} in your favorite text editor. You'll notice quite a few constructions we haven't seen before. First, note how we define a module. The syntax {\tt module Oturtle = } is much like a let binding, but for modules. The functions and types defined by the class are enclosed within the {\tt struct... end} construction. You can include values within a module as well.

Defining a class operates in much the same way. The {\tt class turtle =} is just like a let-binding except for classes.\footnote{Note that classes do not have to be defined within modules.} We can also have the turtle take arguments to initialize it. Consider the following alternative definition of a turtle:

\beforeverb
\begin{verbatim}
class turtle xi yi = object (self)
  val mutable x = xi
  val mutable y = yi
  ...
end
\end{verbatim}
\afterverb

Now, to create the object, we would call:
\beforeverb
\begin{verbatim}
let bob = new Oturtle.turtle 0 0;;
\end{verbatim}
\afterverb
which will create {\tt bob} in the bottom-left corner of the screen.

Within class definitions, all our values and methods are contained
within the {\tt object... end} construction. The {\tt (self)} lets us
call the object within it's definition, just like we would call it
outside of the class definition. For example, consider the definition
of {\tt step}, which calls {\tt self\#advance}. In general, we could
call it anything, not just {\tt self}, but ``self'' is very common,
and it's not generally good form to call it something else unless it
really makes sense to do so.

\section{The {\tt Str} module}

There's one more module you might want to be familiar with, that's quite common in OCaml coding. It's the {\tt Str} module, and it allows for a lot of functionality that object-oriented programmers would expect to deal with strings.
To define methods or values, we use the {\tt method} or {\tt val} keywords, again, just like let-bindings except for methods and values.

Note that, within both method and class definitions, we do not use semicolons to denot the end of a definition; methods and classes are all defined within a single ``line'' of code.

\section{Debugging}

Because class definitions do not use semicolons to denote the end of lines, figuring out how to define methods that are more than very simple statements can get a little complicated. In general, you can always enclose code in more parentheses to help the compiler figure it out, especially in {\tt if} or {\tt match} clauses.

While it's generally nasty to include more than necessary, using the absolute minimum isn't necessarily recommended either. You want to use exactly the number necessary to make the code clear to both reader and compiler. Sometimes you do have to give up a little readability so that it will compile, but that's often\footnote{not always!} a sign that your code is messy to begin with.

\section{Glossary}

Words

\section{Exercises}

Exercises


\chapter{Case study: data structure selection}

\section{Word frequency analysis}
\label{analysis}

As usual, you should at least attempt the following exercises
before you read my solutions.

\begin{ex}
Write a program that reads a file, breaks each line into
words, strips whitespace and punctuation from the words, and
converts them to lowercase.

\index{string module}
\index{module!string}

Hint: The {\tt Str} module will probably proove useful here.
\end{ex}


\begin{ex}

\index{Project Gutenberg}

Go to Project Gutenberg (\url{gutenberg.net}) and download 
your favorite out-of-copyright book in plain text format.

\index{plain text}
\index{text!plain}

Modify your program from the previous exercise to read the book
you downloaded, skip over the header information at the beginning
of the file, and process the rest of the words as before.

Then modify the program to count the total number of words in
the book, and the number of times each word is used.

\index{word frequency}
\index{frequency!word}

Print the number of different words used in the book.  Compare
different books by different authors, written in different eras.
Which author uses the most extensive vocabulary?
\end{ex}


\begin{ex}
Modify the program from the previous exercise to print the
20 most frequently-used words in the book.
\end{ex}


\begin{ex}
Modify the previous program to read a word list and then print all the words in the book that
are not in the word list.  How many of them are typos?  How many of
them are common words that {\em should} be in the word list, and how
many of them are really obscure?
\end{ex}


\section{Random numbers}

\index{random number}
\index{number, random}
\index{deterministic}
\index{pseudorandom}

Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be {\bf deterministic}.
Determinism is usually a good thing, since we expect the same
calculation to yield the same result.  For some applications, though,
we want the computer to be unpredictable.  Games are an obvious
example, but there are more.

Making a program truly nondeterministic turns out to be not so easy,
but there are ways to make it at least seem nondeterministic.  One of
them is to use algorithms that generate {\bf pseudorandom} numbers.
Pseudorandom numbers are not truly random because they are generated
by a deterministic computation, but just by looking at the numbers it
is all but impossible to distinguish them from random.

\index{random module}
\index{module!random}

The {\tt Random} module provides functions that generate
pseudorandom numbers (which I will simply call ``random'' from
here on).

\index{random function}

To begin, you must initialize the random number generator. To do so, 
call {\tt Random.self\_init}. It takes a unit argument and returns a 
unit. There are other methods of initialization, but this is arguably
the ``most random.'' (The other methods take ``seeds'' and will return 
the same sequence every time for a given seed.)

We can then return random integers, floots, booleans, or other number types we haven't covered. With the exception of booleans, all of them take one argument, or the same type it will return, as an upper bound. Each function will return a random number between 0 and the bound. Conveniently, each of the functions is named by type.
\beforeverb
\begin{verbatim}
# Random.int 10;;
- : int = 5
# Random.float 1.0;;
- : float = 0.438748135348833446
# Random.bool ();;
- : bool = false;;
\end{verbatim}
\afterverb

\begin{ex}

\index{histogram!random choice}

Write a function named \verb"histchoose" that takes
a histogram as defined in Section~\ref{histogram} and returns a 
random value from the histogram, chosen with probability
in proportion to frequency.  For example, for this histogram:

\beforeverb
\begin{verbatim}
# let t = ["a"; "a"; "b"];
# let h = histogram(t);
# histprint h;;
b:1
a:2
\end{verbatim}
\afterverb
%
your function should choose {\tt "a"} with probability $2/3$ and {\tt "b"}
with probability $1/3$.
\end{ex}

\section{Word histogram}

Here is a program that reads a file and builds a histogram of the
words in the file:

\index{histogram!word frequencies}

\beforeverb
\begin{verbatim}
#load "str.cma";;
Random.self_init ();;

let r_punc = "[]\\$\\^\\.\\*\\+\\?{}|:;'\"<>,/\\ \\[=_@#%&!()-]+";;
let strip = Str.global_replace (Str.regexp r_punc) "";;

let addfunct h v k = 
	if (Hashtbl.mem h k)
	then let cntr = (Hashtbl.find h k + v)
		in Hashtbl.replace h k cntr
	else Hashtbl.add h k 1;;

let histogram s = 
	let wordlist = Str.split (Str.regexp "[\t\n ]+") (strip (String.lowercase s)) in
	let hist = Hashtbl.create 1 in
	List.iter (addfunct hist 1) wordlist;
	hist;;

let hist_add h2 h1 =
	Hashtbl.iter (fun k v -> addfunct h1 v k) h2;;

let hist_print tbl = 
	Hashtbl.iter (fun key value ->
			print_string (key^":"^(string_of_int value)^"\n"))
		tbl;;

let hist_of_file filename =
	let in_chan = open_in filename in
	let hist = histogram (input_line in_chan) in
	let done_flag = ref false in
	while not !done_flag do
		try (
		let line = input_line in_chan in
		hist_add (histogram line) hist)
		with End_of_file -> done_flag := true
	done;
	hist;;

let sherlock_hist = hist_of_file "sherlock.txt"
\end{verbatim}
\afterverb
%
This program reads {\tt sherlock.txt}, which contains the text of {\em
  The Adventures of Sherlock Holmes} by Sir Arthur Conan Doyle.

\index{Doyle, Sir Arthur Conan}

\verb"hist_of_file" loops through the lines of the file, passing them one at a time to \verb"histogram", and the result is added to an accumulating histogram.

\index{accumulator!histogram}
\index{traversal}
\index{update!histogram}

To count the total number of words in the file, we can add up
the frequencies in the histogram:

\beforeverb
\begin{verbatim}
let total_words h = Hashtbl.fold (fun k v p -> p+v) h 0;;
\end{verbatim}
\afterverb
%
The number of different words is just the number of items in
the dictionary:

\beforeverb
\begin{verbatim}
let different_words h = Hashtbl.length h;;
\end{verbatim}
\afterverb
%
Here is some code to print the results:

\beforeverb
\begin{verbatim}
let print_info h = 
	print_string ("Total number of words: "^(string_of_int (total_words h)));
	print_newline();
	print_string ("Number of different words: "^(string_of_int (different_words h)));
	print_newline();;
\end{verbatim}
\afterverb
%
And the results:

\beforeverb
\begin{verbatim}
Total number of words: 104465
Number of different words: 8413
\end{verbatim}
\afterverb
%

\section{Most common words}

To find the most common words, we can convert the histogram to a list, then sort it.

\beforeverb
\begin{verbatim}
let list_of_hist h = Hashtbl.fold (fun k v acc -> (k, v) :: acc) h [];;

let most_common_words h = List.sort
	(fun (k1, v1) (k2, v2) -> -(compare v1 v2)) (list_of_hist h);;\end{verbatim}
\afterverb
%
Here is a recursive function that prints the ten most common words:

\beforeverb
\begin{verbatim}
let print_ten l = 
	let rec print_helper l i = 
		if i = 10
		then ()
		else (
			let k, v = List.hd l in (
			print_string (k^":\t"^(string_of_int v));
			print_newline());
			print_helper (List.tl l) (i+1)
		)
	in print_helper l 0;;
\end{verbatim}
\afterverb
%
And here are the results from {\em The Adventures of Sherlock Holmes}:

\beforeverb
\begin{verbatim}
The ten most common words are:
the:	5619
and:	3000
i:	2994
to:	2681
of:	2653
a:	2624
in:	1759
that:	1735
it:	1695
you:	1473
\end{verbatim}
\afterverb

\section{Labelled and Optional Parameters}

\index{optional parameter}
\index{parameter!optional}
\index{parameter!labelled}
\index{labelled parameter}

It is possible to write functions with optional arguments. In order to do so, though, we must learn how to use {\em labelled arguments} first. Labelled arguments, rather than appearing in a specific order, are given specific titles. As a trivial example, let's look at this subtraction function:

\beforeverb
\begin{verbatim}
# let sub ~num1:x ~num2:y = x-y;;
val add : num1:int -> num2:int -> int = <fun>
\end{verbatim}
\afterverb
The syntax for each argument is that the label is to the left of the colon, and the variable within the function is to the right of the colon. As shorthand, we can write {\tt ~varname} instead of {\tt ~varname:varname}. Now let's now see how these arguments work.
\beforeverb
\begin{verbatim}
# sub 3 2;;
- : int = 1
# sub 2 3;;
- : int = -1
# sub ~num1:3 ~num2:2;;
- : int = 1
# sub ~num2:2 ~num1:3;;
- : int = 1
# let num1 = 3 and num2 = 2;;
# sub num2 num1
- : int = -1
# sub ~num2 ~num1
- : int = 1
\end{verbatim}
\afterverb
As you can see, you can call the function normally, and it's the argument order that matters. However, if you use labels, and the argument order doesn't.

You can also have functions that mix labelled and unlabelled arguments. Consider this function, which takes a string and extracts a substring of length {\tt len} starting at position {\tt pos}
\beforeverb
\begin{verbatim}
# let substr str ~len:l ~start:s = String.sub str s l
# substr "Hello" 3 1;;
- : string = "ell"
# substr "Hello" ~start:1 ~len:3;;
- : string = "ell"
# substr ~start:1 "Hello" ~len:3;;
- : string = "ell"
\end{verbatim}
\afterverb
If you have multiple unlabelled arguments, then the order between them matters, but you can still do whatever you'd like with the labelled arguments.

Optional arguments work much the same way, except you give the labelled value a default value. For example, here's a simple increment function:
\beforeverb
\begin{verbatim}
# let bump ?i:(i=1) x = x+i;;
val bump : ?i:int -> int -> int = <fun>
# bump 3;;
- : int = 4
# bump 3 ~i:10;;
- : int = 13;;
# bump 1 3;;
Error: The function applied to this argument has type ?i:int -> int
This argument cannot be applied without label
\end{verbatim}
\afterverb
Note that the optional argument comes first in the funciton definition. An optional argument cannot be the last argument of the function definition, or your argument won't actually be optional:
\beforeverb
\begin{verbatim}
# let bump x ?i:(i=1) = x+i;;
Warning X: this optional argument cannot be erased
# bump 3 ~i:2;;
- : int = 5
# bump 3;;
- : ?i:int -> int = <fun>
\end{verbatim}
\afterverb
Not really all that useful, as an optional argument goes. If all your arguments are optional, you should include a unit at the end of your function definiton.

Here is a function that prints the most common words in a histogram, which defaults to printing ten:

\beforeverb
\begin{verbatim}
let print_most_common ?x:(x=10) l = 
	print_string "The ten most common words are:\n";
	let rec print_helper l i = 
		if i = x
		then ()
		else (
			let k, v = List.hd l in (
			print_string (k^":\t"^(string_of_int v));
			print_newline());
			print_helper (List.tl l) (i+1)
		)
	in print_helper l 0;;\end{verbatim}
\afterverb

\index{default value}
\index{value!default}

Note that, in this case, and many others, we could not use the optional argument but instead write the general case and use currying to define a more specific function:
\beforeverb
\begin{verbatim}
let print_most_common x l = 
	(function as defined above)

let print_ten = print_most_common 10;;
\end{verbatim}
\afterverb

\section{Hashtable subtraction}

\index{hashtbale!subtraction}
\index{subtraction!hashtable}

Finding the words from the book that are not in the word list
from {\tt words.txt} is a problem you might recognize as set
subtraction; that is, we want to find all the words from one
set (the words in the book) that are not in another set (the
words in the list).

{\tt subtract} takes hashtables {\tt h1} and {\tt h2} and returns a
new hashtable that contains all the keys from {\tt h1} that are not
in {\tt h2}.

\beforeverb
\begin{verbatim}
let hash_subtract h1 h2 =
	let h = Hashtbl.create 3 in
	let f k v = if not (Hashtbl.mem h2 k)
		then Hashtbl.add h k v in
	Hashtbl.iter f h1; h;;
\end{verbatim}
\afterverb
%
To find the words in the book that are not in {\tt words.txt},
we can use \verb"hist_of_file" to build a histogram for
{\tt words.txt}, and then subtract:

\beforeverb
\begin{verbatim}
let words_hist = hist_of_file "words.txt";;
let unlisted_words = hash_subtract sherlock_hist words_hist;;
print_string "The words in the book that aren't in the word list are:\n"
hist_print unlisted_words;;
\end{verbatim}
\afterverb
%
% Here are some of the results from {\em The Adventures of Sherlock Holmes}:
% %DO THIS
% \beforeverb
% \begin{verbatim}
% Sike!
% \end{verbatim}
% \afterverb
% %
% Some of these words are names and possessives.  Others, like
% ``rencontre,'' are no longer in common use.  But a few are common
% words that should really be in the list!

% \begin{ex}
% 
% \index{set}
% \index{type!set}
% %Look this up!
% OCaml provides a data structure called {\tt set} that provides many
% common set operations.  Read the documentation at
% \url{docs.python.org/lib/types-set.html} and write a program
% that uses set subtraction to find words in the book that are not in
% the word list.
% \end{ex}


\section{Random words}
\label{randomwords}

\index{histogram!random choice}

To choose a random word from the histogram, the simplest (at least, conceptually) algorithm
is to build a list with multiple copies of each word, according
to the observed frequency, and then choose from the list:
%do this
\beforeverb
\begin{verbatim}
let build_list h = 
	let rec list_builder_helper k v l = 
		if v = 0 then l
		else list_builder_helper k (v-1) (k::l)
	in Hashtbl.fold list_builder_helper h [];;

let hist_random_word h = 
	let l = build_list h in
	List.nth l (Random.int (List.length l))\end{verbatim}
\afterverb
%

\begin{ex}
\label{randhist}

\index{algorithm}

This algorithm works, but it is not very efficient; each time you
choose a random word, it rebuilds the list, which is as big as
the original book.  An obvious improvement is to build the list
once and then make multiple selections, but the list is still big.

An alternative is:

\begin{enumerate}

\item Determine the total number of words, $len$, and pick a random integer between $0$ and $len$.

\item Create a reference integer which is initialized to 0.
  
\item Iterate over the hashtable ({\tt Hashtbl.iter}!), incrementing the reference integer by the value for each key, selecting the word it's processing when the reference integer exceeds the random integer. (You might want a reference string to store the selected word.)

\end{enumerate}

Write a program that uses this algorithm to choose a random
word from the book.
\end{ex}



\section{Markov analysis}

\index{Markov analysis}

If you choose words from the book at random, you can get a
sense of the vocabulary, you probably won't get a sentence:
% do this
\beforeverb
\begin{verbatim}
believe brilliant fact if bedrooms my thank moss to out
\end{verbatim}
\afterverb
%
A series of random words seldom makes sense because there
is no relationship between successive words.  For example, in
a real sentence you would expect an article like ``the'' to
be followed by an adjective or a noun, and probably not a verb
or adverb.

One way to measure these kinds of relationships is Markov
analysis\footnote{This case study is based on an example from
  Kernighan and Pike, {\em The Practice of Programming}, 1999.}, which
characterizes, for a given sequence of words, the probability of the
word that comes next.  For example, the song {\em Eric, the Half a
  Bee} begins:

\begin{quote}
Half a bee, philosophically, \\
Must, ipso facto, half not be. \\
But half the bee has got to be \\
Vis a vis, its entity. D'you see? \\
\\
But can a bee be said to be \\
Or not to be an entire bee \\
When half the bee is not a bee \\
Due to some ancient injury? \\
\end{quote}
%
In this text,
the phrase ``half the'' is always followed by the word ``bee,''
but the phrase ``the bee'' might be followed by either
``has'' or ``is''.

\index{prefix}
\index{suffix}
\index{mapping}

The result of Markov analysis is a mapping from each prefix
(like ``half the'' and ``the bee'') to all possible suffixes
(like ``has'' and ``is'').

\index{random text}
\index{text!random}

Given this mapping, you can generate a random text by
starting with any prefix and choosing at random from the
possible suffixes.  Next, you can combine the end of the
prefix and the new suffix to form the next prefix, and repeat.

For example, if you start with the prefix ``Half a,'' then the
next word has to be ``bee,'' because the prefix only appears
once in the text.  The next prefix is ``a bee,'' so the
next suffix might be ``philosophically,'' ``be'' or ``due.''

In this example the length of the prefix is always two, but
you can do Markov analysis with any prefix length.  The length
of the prefix is called the ``order'' of the analysis.

\begin{ex}
Markov analysis:

\begin{enumerate}

\item Write a program to read a text from a file and perform Markov
analysis.  The result should be a dictionary that maps from
prefixes to a collection of possible suffixes.  The collection
might be a list, tuple, or dictionary; it is up to you to make
an appropriate choice.  You can test your program with prefix
length two, but you should write the program in a way that makes
it easy to try other lengths.

\item Add a function to the previous program to generate random text
based on the Markov analysis.  Here is an example from {\em The Adventures of Sherlock Holmes}
with prefix length 2:

\begin{quote}
anything else. There you are. You'll know all about it presently. Jump up here. All right, John; we shall call at the Hotel Cosmopolitan. Pray
\end{quote}

For this example, I left the punctuation attached to the words.
The result is almost syntactically correct, but not quite.
Semantically, it almost makes sense, but not quite.

What happens if you increase the prefix length?  Does the random
text make more sense?

\index{mash-up}

\item Once your program is working, you might want to try a mash-up:
if you analyze text from two or more books, the random
text you generate will blend the vocabulary and phrases from
the sources in interesting ways.

\end{enumerate}
\end{ex}


\section{Data structures}

\index{data structure}

Using Markov analysis to generate random text is fun, but there is
also a point to this exercise: data structure selection.  In your
solution to the previous exercises, you had to choose:

\begin{itemize}

\item How to represent the prefixes.

\item How to represent the collection of possible suffixes.

\item How to represent the mapping from each prefix to
the collection of possible suffixes.

\end{itemize}

Ok, the last one is the easy; the only mapping type we have
seen is a hashtable, so it is the natural choice.

For the prefixes, the most obvious options are string,
list of strings, or tuple of strings.  For the suffixes,
one option is a list; another is a histogram (hashtable).

\index{implementation}

How should you choose?  The first step is to think about
the operations you will need to implement for each data structure.
For the prefixes, we need to be able to remove words from
the beginning and add to the end.  For example, if the current
prefix is ``Half a,'' and the next word is ``bee,'' you need
to be able to form the next prefix, ``a bee.''

For the collection of suffixes, the operations we need to
perform include adding a new suffix (or increasing the frequency
of an existing one), and choosing a random suffix.

Adding a new suffix is equally easy for the list implementation
or the histogram.  Choosing a random element from a list
is easy; choosing from a histogram is harder to do
efficiently (see Exercise~\ref{randhist}), but we also already built 
a function that does it.

So far we have been talking mostly about ease of implementation,
but there are other factors to consider in choosing data structures.
One is run time.  Sometimes there is a theoretical reason to expect
one data structure to be faster than other; for example, random access 
is faster in dictionaries and arrays than in lists.

But often you don't know ahead of time which implementation will
be faster.  One option is to implement both of them and see which
is better.  This approach is called {\bf benchmarking}.  A practical
alternative is to choose the data structure that is
easiest to implement, and then see if it is fast enough for the
intended application.  % If so, there is no need to go on.  If not,
% there are tools, that can identify %find one!
% the places in a program that take the most time.

\index{benchmarking}

The other factor to consider is storage space.  For example, using a
histogram for the collection of suffixes might take less space because
you only have to store each word once, no matter how many times it
appears in the text.  In some cases, saving space can also make your
program run faster, and in the extreme, your program might not run at
all if you run out of memory.  But for many applications, space is a
secondary consideration after run time.

One final thought: in this discussion, I have implied that
we should use one data structure for both analysis and generation.  But
since these are separate phases, it would also be possible to use one
structure for analysis and then convert to another structure for
generation.  This would be a net win if the time saved during
generation exceeded the time spent in conversion.


\section{Debugging}
\index{debugging}

When you are debugging a program, and especially if you are
working on a hard bug, there are four things to try:

\begin{description}

\item[reading:] Examine your code, read it back to yourself, and
check that it says what you meant to say.

\item[running:] Experiment by making changes and running different
versions.  Often if you display the right thing at the right place
in the program, the problem becomes obvious, but sometimes you have to
spend some time to build scaffolding.

\item[ruminating:] Take some time to think!  What kind of error
is it: syntax, runtime, semantic?  What information can you get from
the error messages, or from the output of the program?  What kind of
error could cause the problem you're seeing?  What did you change
last, before the problem appeared?

\item[retreating:] At some point, the best thing to do is back
off, undoing recent changes, until you get back to a program that
works and that you understand.  Then you can start rebuilding.

\end{description}

Beginning programmers sometimes get stuck on one of these activities
and forget the others.  Each activity comes with its own failure
mode.

\index{typographical error}

For example, reading your code might help if the problem is a
typographical error, but not if the problem is a conceptual
misunderstanding.  If you don't understand what your program does, you
can read it 100 times and never see the error, because the error is in
your head.

\index{experimental debugging}

Running experiments can help, especially if you run small, simple
tests.  But if you run experiments without thinking or reading your
code, you might fall into a pattern I call ``random walk programming,''
which is the process of making random changes until the program
does the right thing.  Needless to say, random walk programming
can take a long time.

\index{random walk programming}
\index{development plan!random walk programming}

You have to take time to think.  Debugging is like an
experimental science.  You should have at least one hypothesis about
what the problem is.  If there are two or more possibilities, try to
think of a test that would eliminate one of them.

Taking a break helps with the thinking.  So does talking.
If you explain the problem to someone else (or even yourself), you
will sometimes find the answer before you finish asking the question.

But even the best debugging techniques will fail if there are too many
errors, or if the code you are trying to fix is too big and
complicated.  Sometimes the best option is to retreat, simplifying the
program until you get to something that works and that you
understand.

Beginning programmers are often reluctant to retreat because
they can't stand to delete a line of code (even if it's wrong).
If it makes you feel better, copy your program into another file
before you start stripping it down.  Then you can paste the pieces
back in a little bit at a time.

Finding a hard bug requires reading, running, ruminating, and
sometimes retreating.  If you get stuck on one of these activities,
try the others.


\section{Glossary}

\begin{description}

\item[deterministic:] Pertaining to a program that does the same
thing each time it runs, given the same inputs.
\index{deterministic}

\item[pseudorandom:] Pertaining to a sequence of numbers that appear
to be random, but are generated by a deterministic program.
\index{pseudorandom}

\item[default value:] The value given to an optional parameter if no
argument is provided.
\index{default value}

\item[override:] To replace a default value with an argument.
\index{override}

\item[benchmarking:] The process of choosing between data structures
by implementing alternatives and testing them on a sample of the
possible inputs.  
\index{benchmarking}

\end{description}

\section{Exercises}

\begin{ex}

\index{word frequency}
\index{frequency!word}
\index{Zipf's law}

The ``rank'' of a word is its position in a list of words
sorted by frequency: the most common word has rank 1, the
second most common has rank 2, etc.

Zipf's law describes a relationship between the ranks and frequencies
of words in natural languages\footnote{See
  \url{wikipedia.org/wiki/Zipf's_law}.}.  Specifically, it
predicts that the frequency, $f$, of the word with rank $r$ is:

\[ f = c r^{-s} \]
%
where $s$ and $c$ are parameters that depend on the language and the
text.  If you take the logarithm of both sides of this equation, you
get:

\index{logarithm}

\[ \log f = \log c - s \log r \]
%
So if you plot $\log f$ versus $\log r$, you should get
a straight line with slope $-s$ and intercept $\log c$.

Write a program that reads a text from a file, counts
word frequencies, and prints one line
for each word, in descending order of frequency, with
$\log f$ and $\log r$.  Use the graphing program of your
choice to plot the results and check whether they form
a straight line.  Can you estimate the value of $s$?
\end{ex}


%%% Topics as yet uncovered:
% Databases/Persistence/Marshalling
% Inheritence
% OS maneuvering (current directory, et cetera)
% GUI

\appendix

% \chapter{Debugging}
% \index{debugging}
% 
% Different kinds of errors can occur
% in a program, and it is useful to distinguish among them
% in order to track them down more quickly:
% 
% \begin{itemize}
% 
% \item Syntax errors are produced by OCaml when it is translating the
%   source code into byte code.  They usually indicate that there is
%   something wrong with the syntax of the program.  Example: Omitting
%   the colon at the end of a {\tt def} statement yields the somewhat
%   redundant message {\tt SyntaxError: invalid syntax}.
% 
% \item Runtime errors are produced by the interpreter if something goes
%   wrong while the program is running.  Most runtime error messages
%   include information about where the error occurred and what
%   functions were executing.  Example: An infinite recursion eventually
%   causes the runtime error ``maximum recursion depth exceeded.''
% 
% \item Semantic errors are problems with a program that runs without
%   producing error messages but doesn't do the right thing.  Example:
%   An expression may not be evaluated in the order you expect, yielding
%   an incorrect result.
% 
% \end{itemize}
% 
% \index{syntax error}
% \index{runtime error}
% \index{semantic error}
% \index{error!compile-time}
% \index{error!syntax}
% \index{error!runtime}
% \index{error!semantic}
% \index{exception}
% 
% The first step in debugging is to figure out which kind of
% error you are dealing with.  Although the following sections are
% organized by error type, some techniques are
% applicable in more than one situation.
% 
% 
% \section{Syntax errors}
% 
% \index{error message}
% 
% Syntax errors are usually easy to fix once you figure out what they
% are.  Unfortunately, the error messages are often not helpful.
% The most common messages are {\tt SyntaxError: invalid syntax} and
% {\tt SyntaxError: invalid token}, neither of which is very informative.
% 
% On the other hand, the message does tell you where in the program the
% problem occurred.  Actually, it tells you where OCaml
% noticed a problem, which is not necessarily where the error
% is.  Sometimes the error is prior to the location of the error
% message, often on the preceding line.
% 
% \index{incremental development}
% \index{development plan!incremental}
% 
% If you are building the program incrementally, you should have
% a good idea about where the error is.  It will be in the last
% line you added.
% 
% If you are copying code from a book, start by comparing
% your code to the book's code very carefully.  Check every character.
% At the same time, remember that the book might be wrong, so
% if you see something that looks like a syntax error, it might be.
% 
% Here are some ways to avoid the most common syntax errors:
% 
% \index{syntax}
% 
% \begin{enumerate}
% 
% \item Make sure you are not using a OCaml keyword for a variable name.
% 
% \index{keyword}
% 
% \item Check that you have a colon at the end of the header of every
% compound statement, including {\tt for}, {\tt while},
% {\tt if}, and {\tt def} statements.
% 
% \index{header}
% \index{colon}
% 
% \item Make sure that any strings in the code have matching
% quotation marks.
% 
% \index{quotation mark}
% 
% \item If you have multiline strings with triple quotes (single or double), make
% sure you have terminated the string properly.  An unterminated string
% may cause an {\tt invalid token} error at the end of your program,
% or it may treat the following part of the program as a string until it
% comes to the next string.  In the second case, it might not produce an error
% message at all!
% 
% \index{multiline string}
% \index{string!multiline}
% 
% \item An unclosed opening operator---\verb+(+, \verb+{+, or
%   \verb+[+---makes OCaml continue with the next line as part of the
%   current statement.  Generally, an error occurs almost immediately in
%   the next line.
% 
% \item Check for the classic {\tt =} instead of {\tt ==} inside
% a conditional.
% 
% \index{conditional}
% 
% \item Check the indentation to make sure it lines up the way it
% is supposed to.  Python can handle space and tabs, but if you mix
% them it can cause problems.  The best way to avoid this problem
% is to use a text editor that knows about Python and generates
% consistent indentation.
% 
% \index{indentation}
% \index{whitespace}
% 
% \end{enumerate}
% 
% If nothing works, move on to the next section...
% 
% 
% \subsection{I keep making changes and it makes no difference.}
% 
% If the interpreter says there is an error and you don't see it, that
% might be because you and the interpreter are not looking at the same
% code.  Check your programming environment to make sure that the
% program you are editing is the one Python is trying to run.
% 
% If you are not sure, try putting an obvious and deliberate syntax
% error at the beginning of the program.  Now run it again.  If the
% interpreter doesn't find the new error, you are not running the
% new code.
% 
% There are a few likely culprits:
% 
% \begin{itemize}
% 
% \item You edited the file and forgot to save the changes before
% running it again.  Some programming environments do this
% for you, but some don't.
% 
% \item You changed the name of the file, but you are still running
% the old name.
% 
% \item Something in your development environment is configured
% incorrectly.
% 
% \item If you are writing a module and using {\tt import},
% make sure you don't give your module the same name as one
% of the standard Python modules.
% 
% \index{module!reload}
% \index{reload function}
% \index{function!reload}
% 
% \item If you are using {\tt import} to read a module, remember
% that you have to restart the interpreter or use {\tt reload}
% to read a modified file.  If you import the module again, it
% doesn't do anything.
% 
% \end{itemize}
% 
% If you get stuck and you can't figure out what is going on, one
% approach is to start again with a new program like ``Hello, World!,''
% and make sure you can get a known program to run.  Then gradually add
% the pieces of the original program to the new one.
% 
% 
% \section{Runtime errors}
% 
% Once your program is syntactically correct,
% Python can compile it and at least start running it.  What could
% possibly go wrong?
% 
% 
% \subsection{My program does absolutely nothing.}
% 
% This problem is most common when your file consists of functions and
% classes but does not actually invoke anything to start execution.
% This may be intentional if you only plan to import this module to
% supply classes and functions.
% 
% If it is not intentional, make sure that you
% are invoking a function to start execution, or execute one from
% the interactive prompt.  Also see the ``Flow of Execution'' section
% below.
% 
% 
% \subsection{My program hangs.}
% \index{infinite loop}
% \index{infinite recursion}
% \index{hanging}
% 
% If a program stops and seems to be doing nothing, it is ``hanging.''
% Often that means that it is caught in an infinite loop or infinite
% recursion.
% 
% \begin{itemize}
% 
% \item If there is a particular loop that you suspect is the
% problem, add a {\tt print} statement immediately before the loop that says
% ``entering the loop'' and another immediately after that says
% ``exiting the loop.''
% 
% Run the program.  If you get the first message and not the second,
% you've got an infinite loop.  Go to the ``Infinite Loop'' section
% below.
% 
% \item Most of the time, an infinite recursion will cause the program
% to run for a while and then produce a ``RuntimeError: Maximum
% recursion depth exceeded'' error.  If that happens, go to the
% ``Infinite Recursion'' section below.
% 
% If you are not getting this error but you suspect there is a problem
% with a recursive method or function, you can still use the techniques
% in the ``Infinite Recursion'' section.
% 
% \item If neither of those steps works, start testing other
% loops and other recursive functions and methods.
% 
% \item If that doesn't work, then it is possible that
% you don't understand the flow of execution in your program.
% Go to the ``Flow of Execution'' section below.
% 
% \end{itemize}
% 
% 
% \subsubsection{Infinite Loop}
% \index{infinite loop}
% \index{loop!infinite}
% \index{condition}
% \index{loop!condition}
% 
% If you think you have an infinite loop and you think you know
% what loop is causing the problem, add a {\tt print} statement at
% the end of the loop that prints the values of the variables in
% the condition and the value of the condition.
% 
% For example:
% 
% \beforeverb
% \begin{verbatim}
% while x > 0 and y < 0 :
%     # do something to x
%     # do something to y
% 
%     print  "x: ", x
%     print  "y: ", y
%     print  "condition: ", (x > 0 and y < 0)
% \end{verbatim}
% \afterverb
% %
% Now when you run the program, you will see three lines of output
% for each time through the loop.  The last time through the
% loop, the condition should be {\tt false}.  If the loop keeps
% going, you will be able to see the values of {\tt x} and {\tt y},
% and you might figure out why they are not being updated correctly.
% 
% 
% \subsubsection{Infinite Recursion}
% \index{infinite recursion}
% \index{recursion!infinite}
% 
% Most of the time, an infinite recursion will cause the program to run
% for a while and then produce a {\tt Maximum recursion depth exceeded}
% error.
% 
% If you suspect that a function or method is causing an infinite
% recursion, start by checking to make sure that there is a base case.
% In other words, there should be some condition that will cause the
% function or method to return without making a recursive invocation.
% If not, then you need to rethink the algorithm and identify a base
% case.
% 
% If there is a base case but the program doesn't seem to be reaching
% it, add a {\tt print} statement at the beginning of the function or method
% that prints the parameters.  Now when you run the program, you will see
% a few lines of output every time the function or method is invoked,
% and you will see the parameters.  If the parameters are not moving
% toward the base case, you will get some ideas about why not.
% 
% 
% \subsubsection{Flow of Execution}
% \index{flow of execution}
% 
% If you are not sure how the flow of execution is moving through
% your program, add {\tt print} statements to the beginning of each
% function with a message like ``entering function {\tt foo},'' where
% {\tt foo} is the name of the function.
% 
% Now when you run the program, it will print a trace of each
% function as it is invoked.
% 
% 
% \subsection{When I run the program I get an exception.}
% \index{exception}
% \index{runtime error}
% 
% If something goes wrong during runtime, Python
% prints a message that includes the name of the
% exception, the line of the program where the problem occurred,
% and a traceback.
% 
% \index{traceback}
% 
% The traceback identifies the function that is currently running,
% and then the function that invoked it, and then the function that
% invoked {\em that}, and so on.  In other words, it traces the
% sequence of function invocations that got you to where you are.  It
% also includes the line number in your file where each of these
% calls occurs.
% 
% The first step is to examine the place in the program where
% the error occurred and see if you can figure out what happened.
% These are some of the most common runtime errors:
% 
% \begin{description}
% 
% \item[NameError:]  You are trying to use a variable that doesn't
% exist in the current environment.
% Remember that local variables are local.  You
% cannot refer to them from outside the function where they are defined.
% 
% \index{NameError}
% \index{TypeError}
% \index{exception!NameError}
% \index{exception!TypeError}
% 
% \item[TypeError:] There are several possible causes:
% 
% \begin{itemize}
% 
% \item  You are trying to use a value improperly.  Example: indexing
% a string, list, or tuple with something other than an integer.
% 
% \index{index}
% 
% \item There is a mismatch between the items in a format string and
% the items passed for conversion.  This can happen if either the number
% of items does not match or an invalid conversion is called for.
% 
% \index{format operator}
% \index{operator!format}
% 
% \item You are passing the wrong number of arguments to a function or method.
% For methods, look at the method definition and
% check that the first parameter is {\tt self}.  Then look at the
% method invocation; make sure you are invoking the method on an
% object with the right type and providing the other arguments
% correctly.
% 
% \end{itemize}
% 
% \item[KeyError:]  You are trying to access an element of a dictionary
% using a key that the dictionary does not contain.
% 
% \index{KeyError}
% \index{exception!KeyError}
% \index{dictionary}
% 
% \item[AttributeError:] You are trying to access an attribute or method
% that does not exist.  Check the spelling!  You can use
% {\tt dir} to list the attributes that do exist.
% 
% If an AttributeError indicates that an object has {\tt NoneType},
% that means that it is {\tt None}.  One common cause is forgetting
% to return a value from a function; if you get to the end of
% a function without hitting a {\tt return} statement, it returns
% {\tt None}.  Another common cause is using the result from
% a list method, like {\tt sort}, that returns {\tt None}.
% 
% \index{AttributeError}
% \index{exception!AttributeError}
% 
% \item[IndexError:] The index you are using
% to access a list, string, or tuple is greater than
% its length minus one.  Immediately before the site of the error,
% add a {\tt print} statement to display
% the value of the index and the length of the array.
% Is the array the right size?  Is the index the right value?
% 
% \index{IndexError}
% \index{exception!IndexError}
% 
% \end{description}
% 
% \index{debugger (pdb)}
% \index{Python debugger (pdb)}
% \index{pdb (Python debugger)}
% 
% The Python debugger ({\tt pdb}) is useful for tracking down
% Exceptions because it allows you to examine the state of the
% program immediately before the error.  You can read
% about {\tt pdb} at \url{docs.python.org/lib/module-pdb.html}.
% 
% 
% \subsection{I added so many {\tt print} statements I get inundated with
% output.}
% 
% \index{print statement}
% \index{statement!print}
% 
% One of the problems with using {\tt print} statements for debugging
% is that you can end up buried in output.  There are two ways
% to proceed: simplify the output or simplify the program.
% 
% To simplify the output, you can remove or comment out {\tt print}
% statements that aren't helping, or combine them, or format
% the output so it is easier to understand.
% 
% To simplify the program, there are several things you can do.  First,
% scale down the problem the program is working on.  For example, if you
% are searching a list, search a {\em small} list.  If the program takes
% input from the user, give it the simplest input that causes the
% problem.
% 
% \index{dead code}
% 
% Second, clean up the program.  Remove dead code and reorganize the
% program to make it as easy to read as possible.  For example, if you
% suspect that the problem is in a deeply nested part of the program,
% try rewriting that part with simpler structure.  If you suspect a
% large function, try splitting it into smaller functions and testing them
% separately.
% 
% \index{testing!minimal test case}
% \index{test case, minimal}
% 
% Often the process of finding the minimal test case leads you to the
% bug.  If you find that a program works in one situation but not in
% another, that gives you a clue about what is going on.
% 
% Similarly, rewriting a piece of code can help you find subtle
% bugs.  If you make a change that you think shouldn't affect the
% program, and it does, that can tip you off.
% 
% 
% \section{Semantic errors}
% \index{semantic error}
% \index{error!semantic}
% 
% In some ways, semantic errors are the hardest to debug,
% because the interpreter provides no information
% about what is wrong.  Only you know what the program is supposed to
% do.
% 
% The first step is to make a connection between the program
% text and the behavior you are seeing.  You need a hypothesis
% about what the program is actually doing.  One of the things
% that makes that hard is that computers run so fast.
% 
% You will often wish that you could slow the program down to human
% speed, and with some debuggers you can.  But the time it takes to
% insert a few well-placed {\tt print} statements is often short compared to
% setting up the debugger, inserting and removing breakpoints, and
% ``stepping'' the program to where the error is occurring.
% 
% \subsection{My program doesn't work.}
% 
% You should ask yourself these questions:
% 
% \begin{itemize}
% 
% \item Is there something the program was supposed to do but
% which doesn't seem to be happening?  Find the section of the code
% that performs that function and make sure it is executing when
% you think it should.
% 
% \item Is something happening that shouldn't?  Find code in
% your program that performs that function and see if it is
% executing when it shouldn't.
% 
% \item Is a section of code producing an effect that is not
% what you expected?  Make sure that you understand the code in
% question, especially if it involves invocations to functions or methods in
% other OCaml modules.  Read the documentation for the functions you invoke.
% Try them out by writing simple test cases and checking the results.
% 
% \end{itemize}
% 
% In order to program, you need to have a mental model of how
% programs work.  If you write a program that doesn't do what you expect,
% very often the problem is not in the program; it's in your mental
% model.
% 
% \index{model, mental}
% \index{mental model}
% 
% The best way to correct your mental model is to break the program
% into its components (usually the functions and methods) and test
% each component independently.  Once you find the discrepancy
% between your model and reality, you can solve the problem.
% 
% Of course, you should be building and testing components as you
% develop the program.  If you encounter a problem,
% there should be only a small amount of new code
% that is not known to be correct.
% 
% 
% \subsection{I've got a big hairy expression and it doesn't
% do what I expect.}
% 
% \index{expression!big and hairy}
% \index{big, hairy expression}
% 
% Writing complex expressions is fine as long as they are readable,
% but they can be hard to debug.  It is often a good idea to
% break a complex expression into a series of assignments to
% temporary variables.
% 
% For example:
% 
% \beforeverb
% \begin{verbatim}
% self.hands[i].addCard(self.hands[self.findNeighbor(i)].popCard())
% \end{verbatim}
% \afterverb
% %
% This can be rewritten as:
% 
% \beforeverb
% \begin{verbatim}
% neighbor = self.findNeighbor(i)
% pickedCard = self.hands[neighbor].popCard()
% self.hands[i].addCard(pickedCard)
% \end{verbatim}
% \afterverb
% %
% The explicit version is easier to read because the variable
% names provide additional documentation, and it is easier to debug
% because you can check the types of the intermediate variables
% and display their values.
% 
% \index{temporary variable}
% \index{variable!temporary}
% \index{order of operations}
% \index{precedence}
% 
% Another problem that can occur with big expressions is
% that the order of evaluation may not be what you expect.
% For example, if you are translating the expression
% $\frac{x}{2 \pi}$ into Python, you might write:
% 
% \beforeverb
% \begin{verbatim}
% y = x / 2 * math.pi
% \end{verbatim}
% \afterverb
% %
% That is not correct because multiplication and division have
% the same precedence and are evaluated from left to right.
% So this expression computes $x \pi / 2$.
% 
% A good way to debug expressions is to add parentheses to make
% the order of evaluation explicit:
% 
% \beforeverb
% \begin{verbatim}
%  y = x / (2 * math.pi)
% \end{verbatim}
% \afterverb
% %
% Whenever you are not sure of the order of evaluation, use
% parentheses.  Not only will the program be correct (in the sense
% of doing what you intended), it will also be more readable for
% other people who haven't memorized the rules of precedence.
% 
% 
% \subsection{I've got a function or method that doesn't return what I
% expect.}
% \index{return statement}
% \index{statement!return}
% 
% If you have a {\tt return} statement with a complex expression,
% you don't have a chance to print the {\tt return} value before
% returning.  Again, you can use a temporary variable.  For
% example, instead of:
% 
% \beforeverb
% \begin{verbatim}
% return self.hands[i].removeMatches()
% \end{verbatim}
% \afterverb
% %
% you could write:
% 
% \beforeverb
% \begin{verbatim}
% count = self.hands[i].removeMatches()
% return count
% \end{verbatim}
% \afterverb
% %
% Now you have the opportunity to display the value of
% {\tt count} before returning.
% 
% 
% \subsection{I'm really, really stuck and I need help.}
% 
% First, try getting away from the computer for a few minutes.
% Computers emit waves that affect the brain, causing these
% symptoms:
% 
% \begin{itemize}
% 
% \item Frustration and rage.
% 
% \index{frustration}
% \index{rage}
% \index{debugging!emotional response}
% \index{emotional debugging}
% 
% \item Superstitious beliefs (``the computer hates me'') and
% magical thinking (``the program only works when I wear my
% hat backward'').
% 
% \index{debugging!superstition}
% \index{superstitious debugging}
% 
% \item Random walk programming (the attempt to program by writing
% every possible program and choosing the one that does the right
% thing).
% 
% \index{random walk programming}
% \index{development plan!random walk programming}
% 
% \end{itemize}
% 
% If you find yourself suffering from any of these symptoms, get
% up and go for a walk.  When you are calm, think about the program.
% What is it doing?  What are some possible causes of that
% behavior?  When was the last time you had a working program,
% and what did you do next?
% 
% Sometimes it just takes time to find a bug.  I often find bugs
% when I am away from the computer and let my mind wander.  Some
% of the best places to find bugs are trains, showers, and in bed,
% just before you fall asleep.
% 
% 
% \subsection{No, I really need help.}
% 
% It happens.  Even the best programmers occasionally get stuck.
% Sometimes you work on a program so long that you can't see the
% error.  A fresh pair of eyes is just the thing.
% 
% Before you bring someone else in, make sure you are prepared.
% Your program should be as simple
% as possible, and you should be working on the smallest input
% that causes the error.  You should have {\tt print} statements in the
% appropriate places (and the output they produce should be
% comprehensible).  You should understand the problem well enough
% to describe it concisely.
% 
% When you bring someone in to help, be sure to give
% them the information they need:
% 
% \begin{itemize}
% 
% \item If there is an error message, what is it
% and what part of the program does it indicate?
% 
% \item What was the last thing you did before this error occurred?
% What were the last lines of code that you wrote, or what is
% the new test case that fails?
% 
% \item What have you tried so far, and what have you learned?
% 
% \end{itemize}
% 
% When you find the bug, take a second to think about what you
% could have done to find it faster.  Next time you see something
% similar, you will be able to find the bug more quickly.
% 
% Remember, the goal is not just to make the program
% work.  The goal is to learn how to make the program work.
% 
% 
% 
\printindex

\clearemptydoublepage
%\blankpage
%\blankpage
%\blankpage


\end{document}
